简体   繁体   中英

How do Ruby operators have normal precedence if they're also methods?

Ruby's operators, like + or * , follow the order of precedence as in mathematics when used in the syntax-sugar form. In the following, * is called before + :

# Syntax-sugar form
5 + 5 * 2 # => 15

In the non-syntax-sugar form, the methods follow the linear order in which they are written. In the following, + is called before * :

# Non-syntax-sugar form
5.+(5).*(2) # => 20

Methods that I define, like the + method as follows, work both with and without the syntax-sugar form:

class WackyInt
  attr_reader :value     

  def initialize(value)
    @value = value
  end

  def +(other)
    WackyInt.new(value + other.value)
  end
end

ONE = WackyInt.new 1
FIVE = WackyInt.new 5

# As operators
ONE + FIVE # => #<WackyInt @number=-4>
# As methods
ONE.+(FIVE) # => #<WackyInt @number=-4>

The defined operators follow the respective order of precedence both in the syntax-sugar form and the non-syntax-sugar form.

How can Ruby parse this?

Tokenizing, parsing, and assigning computational precedence is separated from calling and executing the methods. What you can overwrite is what is done when a method is called. That does not change how a Ruby code is tokeninzed or parsed, and hence computational precedence is not affected by that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM