簡體   English   中英

我不理解Ruby運算符的概念。 '<'和'xyz'方法有什么區別?

[英]I don't understand the concept of Ruby operators. What is the difference between '<' and 'xyz' method?

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

我不明白為什么'<'方法正常工作而'xyz'方法返回錯誤?

在Ruby < > + - etc中是運算符,你可以在沒有點的情況下調用運算符,當然你可以重新定義那些運算符(你在這里做什么)。

xyz是一個字符串的情況下,當沒有點ruby調用時,不同的處理方式。

a.xyz b評估為a.xyz(b)

a xyz b求值為a(xyz(b))並且因為全局作用域是Object ,所以將為undefined method 'xyz' for main:Object拋出undefined method 'xyz' for main:Object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM