【问题标题】:Calling methods a la Object#send, but not breaking when given a nonexistent method (Ruby)调用对象#send的方法,但在给定不存在的方法时不会中断(Ruby)
【发布时间】: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 的方式调用确实存在的方法,而对于传入的方法则不存在,我只是希望程序不要中断。有谁知道这样做的吗?

【问题讨论】:

    标签: ruby send


    【解决方案1】:

    如果您使用的是 Rails,可以尝试查看 try

    【讨论】:

      【解决方案2】:

      您可以使用method_missing

      def respond_to_missing?(*)
        true
      end
      
      private
      
      def method_missing(*)
      end
      

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

      如需更强大的实现 NullObject 模式的方法,请查看 Avdi Grimm 的 naught gem。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-09
        • 1970-01-01
        • 2015-06-21
        • 1970-01-01
        相关资源
        最近更新 更多