我尝试使用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
方式调用确实存在的方法,对于不存在的方法,我只是希望程序不要破坏。有谁知道这样做的事情?
答案 0 :(得分:1)
如果您正在使用Rails,可以尝试查看try
答案 1 :(得分:1)
您可以使用method_missing
def respond_to_missing?(*)
true
end
private
def method_missing(*)
end
这将使您的对象返回nil
以响应任何未定义的方法。
有关实现NullObject模式的更强大方法,请查看Avdi Grimm的naught gem。