【发布时间】:2015-08-28 20:17:06
【问题描述】:
我正在尝试使用 send 方法在 Ruby 中做这样的事情:
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.
显然,传入不存在的 :baz 会返回错误,但我想知道是否有办法以类似 send 的方式调用确实存在的方法,而对于传入的方法则不存在,我只是希望程序不要中断。有谁知道这样做的吗?
【问题讨论】: