将方法调用为la Object#send,但在给定不存在的方法时不中断(Ruby)

将方法调用为la Object#send,但在给定不存在的方法时不中断(Ruby),ruby,send,Ruby,Send,我尝试在Ruby中使用send方法执行类似的操作: class Foo def bar puts "Foo's bar method" end end foo = Foo.new foo.send :bar # => "Foo's bar method" foo.send :baz # => NoMethodError: undefined method `baz' for #<Foo:0x00000000a2e720> #

我尝试在Ruby中使用
send
方法执行类似的操作:

class Foo
  def bar
    puts "Foo's bar method"
  end
end

foo = Foo.new
foo.send :bar # => "Foo's bar method"
foo.send :baz # => NoMethodError: undefined method `baz' for #<Foo:0x00000000a2e720>
              # Is there a way I can send :baz to foo without the program breaking?
              # I.e., don't call anything if the given method doesn't exist.
class-Foo
def棒
放置“Foo's bar方法”
结束
结束
foo=foo.new
foo.send:bar#=>“foo的bar方法”
foo.send:baz#=>NoMethodError:for的未定义方法'baz'#
#有没有一种方法可以在不中断程序的情况下将:baz发送到foo?
#也就是说,如果给定的方法不存在,就不要调用任何东西。

显然,传入不存在的
:baz
会返回一个错误,但我想知道是否有一种方法可以调用确实存在的方法,以类似于
的方式发送
,对于传入的不存在的方法,我只是希望程序不要中断。有人知道这样做的东西吗?

如果您正在使用Rails,您可以尝试查看您可以使用的

这将使对象返回
nil
,以响应任何未定义的方法


要获得更强大的实现NullObject模式的方法,请查看Avdi Grimm的gem。

这确实不错,但正如@AndrewKozin所说,仅限于Rails。这也不像看上去那么好
def respond_to_missing?(*)
  true
end

private

def method_missing(*)
end