我不理解Ruby运算符的概念。 '<'之间的区别是什么?和'xyz'方法?

时间:2014-04-22 23:35:04

标签: ruby operators

class Computation

  def initialize(&block)
    @action = block
  end

  def result
    @result ||= @action.call
  end

  def xyz(other)

  end

  def <(other)
    result < other.result
  end


end

a = Computation.new { 1 + 1 }
b = Computation.new { 4*5 }



p a < b  #=> true
p a xyz b #=> `<main>': undefined method `xyz' for main:Objec

我不明白为什么&#39;&lt;&#39;方法正常工作和&#39; xyz&#39;方法返回错误?

1 个答案:

答案 0 :(得分:2)

在Ruby < > + -等中的

是运算符,你可以在没有点的情况下调用运算符,当然你可以重新定义那些运算符(你在这里做的是什么)。

如果xyz是一个字符串,并且在没有点的情况下调用ruby会以不同的方式处理它。

a.xyz b评估为a.xyz(b)

a xyz b评估为a(xyz(b)),由于全局范围为Object,因此会undefined method 'xyz' for main:Object