接受所有方法名称并将其打印出来的对象

问题描述 投票:0回答:1

我想创建一个接受方法名称并打印出来的对象。我应该可以调用任何方法。例如,

obj.hello("was")
# => called hello with argument 'was'

obj.ok(["df", 1])
# => called ok with argument ["df", 1]

我不想提前定义hellook

那可能吗?

ruby
1个回答
6
投票

简单:

class Noop
  def method_missing(m, *args)
    puts "#{m} #{args.inspect}"
  end
end

Noop.new.foo 
# => foo []
Noop.new.bar(1,2,3) 
# => bar [1, 2, 3]

当您调用不存在的方法时,会在每个Ruby对象上调用method_missing。它通常最终由Object(所有东西的超类)处理,它引发了NoMethodError

请注意,这不适用于其祖先(类,模块,对象,内核,BasicObject)提供的方法,您可以通过以下方法检查:

class Noop
  puts self.instance_methods.inspect
  puts self.methods.inspect

  def method_missing(m, *args)
    puts "#{m} #{args.inspect}"
  end
end
© www.soinside.com 2019 - 2024. All rights reserved.