Ruby is a language with strong expressive power, this is proud of its extraordinarily rich operator and grammatical sugars, although Ruby has always been one of its philosophies with the least surprising principle, but it is often seen as a surprising and difficult to understand code, which may be because of its operator and statement precedence understanding caused, I'll talk to you today. The precedence of Ruby operators and statements.
First look at a simple code and guess what its output is.
Copy Code code as follows:
Many people must think the result is Hash, but the result is empty, do not believe you can try in IRB.
Look at a piece of code again.
Copy Code code as follows:
Puts "5 && 3 is #{5 && 3}"
Puts "5 and 3 is #{5 and 3}"
A = 5 && 3
b = 5 and 3
Puts "A is #{a}"
Puts "B is #{b}"
The result:
Copy Code code as follows:
5 && 3 is 3
5 and 3 is 3
A is 3
B is 5
Do you think it's strange that B is 5 instead of 3?
If you're wondering about these two examples, it means you don't have a thorough understanding of the precedence of some of Ruby's operators and statements. Puts {}.class is actually equivalent to (puts {}). class-> Nil.class So the output is empty. {} is equivalent to an empty block, with precedence and method puts combined. The precedence of && and and is different, and the precedence order of = number is compared, && > = > and, so a = 5 && 3 equals a = (5 && 3), and B = 5 and 3 are equal to (b = 5) and 3, so the values of the results A and B are different.
The following table is a prioritized list of operators and statements that are common in Ruby, descending from top to bottom.
Ruby operators (highest to lowest precedence)
A few easy to remember principles:
1. The priority of keyword classes such as if and is lower than the symbolic class;
2. Assignment symbol = | | = Equal priority is also lower, after the key word class;
3.[] []= element references have very high precedence.