【问题标题】:Ruby operator overloading method from blockRuby 运算符从块中重载方法
【发布时间】:2012-04-27 09:23:41
【问题描述】:

我使用的是 Ruby 1.9.2。例如我有课:

class Test
  def ==(param)
    # some process
  end

  def bar(param)
    puts "foo bar #{param}"
  end
end

我可以使用 bar 方法调用:

Test.new.instance_eval{ bar 'celona' }

但我不能像块一样执行 == 方法

Test.new.instance_eval{ == "foo" }

我遇到了语法错误,意外 tEQ

【问题讨论】:

    标签: ruby-on-rails ruby metaprogramming dsl


    【解决方案1】:

    以下内容对我有用:

    class Test
      def ==(param)
        p "You put #{param}"
      end
    end
    
    Test.new.instance_eval{|a|  a == "foo" }
    => "You put foo"
    

    解决方案实际上取决于您的用例。

    编辑实例化类时也是如此。

    b = Test.new
    b == "foo"
    => "You put foo"
    

    你也可以使用self

    Test.new.instance_eval{self == "foo" }
    

    我不完全确定原因,但我猜== 方法需要一个明确的被调用者,它无法推断出self

    【讨论】:

    • 感谢您的回答,但使用 Test.new.instance_eval{self == "foo" } 我不能像 Test.new.instance_eval{bar == "foo" } 那样调用 bar 本身一种方法
    • 那是因为 bar 返回一个字符串。然后,您将 bar 返回的字符串与“foo”进行比较。如果您将 self 作为调用 bar 中的最后一行,那么它将返回您正在执行的 test 的实例。
    【解决方案2】:

    你可以试试:

    Test.new.send("==", "foo")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 2010-12-23
      • 2010-12-21
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多