调用方法一个对象#send,但在给定一个不存在的方法时不会破坏(Ruby)

时间:2015-06-12 18:04:11

标签: ruby send

我尝试使用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方式调用确实存在的方法,对于不存在的方法,我只是希望程序不要破坏。有谁知道这样做的事情?

2 个答案:

答案 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。