Make ruby ​​object on arbitrary messages?

Is there a python equivalent __getattr__in ruby ​​(for finding methods at least)?

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

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

So it could be something like:

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

x = X.new()
x.some_method("some args")
+3
source share
4 answers

Yes. If the object does not respond to the message, Ruby will send the message method_missingusing the message and argument selector to the recipient:

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'

Note that if you define method_missing, you must also define respond_to_missing?accordingly. Otherwise, you will get strange behavior as follows:

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

In this particular case, we process all messages, so we can simply define it as follows:

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

x.respond_to?(:foo) # => true
+7
source
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"]
+5
source

IIRC, method_missing ruby, . , .

+2
class Test
  def say
     puts "hi"
  end
end

say

obj = Test.new
obj.send "say"

obj.respond_to? "say"

,

if (obj.respond_to? "say")
  obj.send "say"
end
-2

All Articles