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;方法返回错误?
答案 0 :(得分:2)
< > + -
等中的是运算符,你可以在没有点的情况下调用运算符,当然你可以重新定义那些运算符(你在这里做的是什么)。
如果xyz
是一个字符串,并且在没有点的情况下调用ruby会以不同的方式处理它。
a.xyz b
评估为a.xyz(b)
a xyz b
评估为a(xyz(b))
,由于全局范围为Object
,因此会undefined method 'xyz' for main:Object