简体   繁体   中英

Ruby && and = operators misudnerstanding

What do you think would be the result of the next expression in Ruby?

    a = 10 && b = 25

Try to calculate in the ming and only then use irb . So, if we take a look at the Ruby documentation aboutOperators Precedence then we will se that && operator has a higher priority than = . So you must think that Ruby will evaluate the expression in the next way:

    a = ((10 && b) = 25)

But Ruby does a job in another way:

    a = (10 && (b = 25))
    # => 25

So, the priority of the = in b = 25 is higher, then && . Can anybody explain why it is happend like so?

This has to do with the way Ruby identifies bareword identifiers

When it comes across an identifier like a , it has to resolve it by checking to see if it is a keyword, local variable or method in that order.

  • keyword - if a is a keyword then use it as a keyword
  • local variable - is there an equal sign to the right of a , then it must be a local variable. If not check if there is any local variable a defined. These points are very important, it is the reason why you can't call writer methods in instance methods without explicitly calling self .

Take for example this code

class Person
  attr_accessor :name #creates both attr_reader name & attr_writer name=(text)

  def print_name
    name # => attr_reader method name is called and returns nil

    name = 'Bola'#even though we have the name= method, it doesn't get called
    #what happens is a local variable name is created instead
    #this is as a result of how ruby interpreted the bareword identifier name
    #not a keyword but has an equal sign so must be a local variable

    name # this time local variable is used instead of method because it is resolved first
  end
end
  • method if it's not resolved as a keyword or local variable then it assumes it's a method and tries to call it.

So this is how the code is evaluated

  • what is to the left of && 10, which it can make sense of
  • compare that 10 to what is on the right of && which is b but it has to evaluate what b is so it resolves it using the procedure I described above which results in local variable b = 25 . Assignment operations always return the values on their right which is 25
  • compare 10 and 25 which returns 25
  • finally a = 25

With that being said && does have higher priority and the = signs are of the same precedence. Hope this explanation was clear.

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