gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:37:43 25 4
gpt4 key购买 nike

我有一个模块定义了一个方法,如果它还没有被定义的话。 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 有关

最佳答案

试试这个。

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

关于Ruby 的 `respond_to?` 在定义之后不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27574249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com