加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Ruby的`respond_to?`在定义后不起作用?

发布时间:2020-12-17 02:07:29 所属栏目:百科 来源:网络整理
导读:我有一个模块定义了一个方法,如果它尚未定义.这是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
我有一个模块定义了一个方法,如果它尚未定义.这是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

预期的结果是嗨,但ruby打印你好.为什么?

也许与Confused about “respond_to?” method有关

解决方法

试试这个.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读