Ruby && and = operators misudnerstanding

空扰寡人 提交于 2021-02-19 05:35:48

问题


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 about Operators 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?


回答1:


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.



来源:https://stackoverflow.com/questions/39805300/ruby-and-operators-misudnerstanding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!