问题
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
- ifa
is a keyword then use it as a keywordlocal variable
- is there an equal sign to the right ofa
, then it must be a local variable. If not check if there is any local variablea
defined. These points are very important, it is the reason why you can't call writer methods in instance methods without explicitly callingself
.
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 isb
but it has to evaluate whatb
is so it resolves it using the procedure I described above which results in local variableb = 25
. Assignment operations always return the values on their right which is25
- compare
10
and25
which returns25
- 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