gpt4 book ai didi

ruby - 让 ruby​​ 对象响应任意消息?

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

在 ruby​​ 中是否有 python __getattr__ 的等价物(至少用于查找方法)?

class X(object):
def __getattr__(self, name):
return lambda x: print("Calling " + name + ": " + x)

x = X()
x.some_method("some args")

所以它可能是这样的:

class X
# .. ??? ..
def default_action(method_name, x)
puts "Calling {method_name}: {x}"
end
end

x = X.new()
x.some_method("some args")

最佳答案

是的。如果对象不响应消息,Ruby 将发送一个带有消息选择器和参数的 method_missing 消息给接收者:

class X
def method_missing(selector, *args, &blk)
puts "The message was #{selector.inspect}."
puts "The arguments were #{args.map(&:inspect).join(', ')}."
puts "And there was #{blk ? 'a' : 'no'} block."
super
end
end

x = X.new
x.some_method('some args', :some_other_args, 42)
# The message was :some_method.
# The arguments were "some args", :some_other_args, 42.
# And there was no block.
# NoMethodError: undefined method `some_method'

x.some_other_method do end
# The message was :some_other_method.
# The arguments were .
# And there was a block.
# NoMethodError: undefined method `some_other_method'

请注意,如果您定义了 method_missing,您还应该相应地定义 respond_to_missing?。否则你会得到这样的奇怪行为:

x.respond_to?(:foo) # => false
x.foo # Works. Huh?

在这种特殊情况下,我们处理所有 消息,因此我们可以简单地定义如下:

class X; def respond_to_missing?(*) true end end

x.respond_to?(:foo) # => true

关于ruby - 让 ruby​​ 对象响应任意消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5273594/

25 4 0
文章推荐: ios - NSTimeZone: "UTC"和 "GMT"之间有什么区别吗?
文章推荐: ios - 唯一标识一个 iOS 用户
文章推荐: ruby - 如何检查
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com