让ruby对象响应任意消息?

ymv*_*ymv 3 ruby

__getattr__在ruby中是否有等效的python (至少可以找到方法)?

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

x = X()
x.some_method("some args")
Run Code Online (Sandbox Code Playgroud)

所以它可能是这样的:

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

x = X.new()
x.some_method("some args")
Run Code Online (Sandbox Code Playgroud)

Jör*_*tag 7

是.如果对象没有响应消息,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'
Run Code Online (Sandbox Code Playgroud)

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

x.respond_to?(:foo) # => false
x.foo               # Works. Huh?
Run Code Online (Sandbox Code Playgroud)

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

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

x.respond_to?(:foo) # => true
Run Code Online (Sandbox Code Playgroud)


ste*_*lag 5

class X
  def method_missing(sym,*args)
    puts "Method #{sym} called with #{args}"
  end
end
a = X.new
a.blah("hello","world")

#=> Method blah called with ["hello", "world"]
Run Code Online (Sandbox Code Playgroud)