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

让ruby对象响应任意消息?

发布时间:2020-12-17 01:44:51 所属栏目:百科 来源:网络整理
导读:在 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 de
在 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",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

(编辑:李大同)

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

    推荐文章
      热点阅读