【问题标题】:Ruby's `respond_to?` do not work just after definition?Ruby 的 `respond_to?` 在定义后不起作用?
【发布时间】:2014-12-19 21:39:49
【问题描述】:

如果尚未定义方法,我有一个定义方法的模块。这就是 ActiveRecord 的属性的情况,因为它们的 getter 和 setter 没有定义为方法。

module B
  def create_say_hello_if_not_exists
    puts respond_to?(:say_hello)
    define_method :say_hello do
      puts 'hello'
    end unless respond_to?(:say_hello)
  end
end

class A
  def say_hello
    puts 'hi'
  end
  puts respond_to?(:say_hello, true)
  extend B
  create_say_hello_if_not_exists
end

A.new.say_hello

预期的结果是hi,但ruby 打印出hello。为什么?

可能与Confused about "respond_to?" method有关

【问题讨论】:

    标签: ruby


    【解决方案1】:

    试试这个。

    module B
      def create_say_hello_if_not_exists
        puts method_defined?(:say_hello)
        define_method :say_hello do
          puts 'hello'
        end unless method_defined?(:say_hello)
      end
    end
    
    class A
      def say_hello
        puts 'hi'
      end
      puts method_defined?( :say_hello )
      extend B
      create_say_hello_if_not_exists
    end
    
    A.new.say_hello
    

    【讨论】:

    • 哇! respond_to?method_defined? 有什么区别?
    • 知道了,方法是在实例上定义的,所以A.new.respond_to? 可以工作。谢谢@kuriouscoder
    【解决方案2】:

    respond_to?(:say_hello) 返回false 的原因是因为class A 具有say_hello 作为实例方法,并且由于您正在扩展class B,所以create_say_hello_if_not_exists 被声明为类方法并且它没有找到say_hello

    将代码更改为以下内容即可。我将class A 中的say_hello 声明为类方法,并以静态方式调用它。

    模块 B def create_say_hello_if_not_exists 把respond_to?(:say_hello) 定义方法:say_hello 做 放“你好” 除非respond_to结束?(:say_hello) 结尾 结尾 A级 def self.say_hello 打“嗨” 结尾 扩展 B create_say_hello_if_not_exists 结尾 A.say_hello

    【讨论】:

      猜你喜欢
      • 2016-05-06
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      相关资源
      最近更新 更多