Introduction to Ruby operators and statement priority, ruby operator priority
Ruby is a language with strong expressive power. It is proud of its rich operators and syntactic sugar. Although Ruby has always regarded the principle of least surprise as one of its philosophies, but it is often surprising that it is difficult to understand the code. This may be because it does not fully understand its operators and statement priorities. Today we will talk about the priority of Ruby operators and statements.
Let's take a look at a simple code and guess what the output is.
Copy codeThe Code is as follows:
Puts {}. class
Many people think that the result is Hash, but in fact the result is empty. If you do not believe it, try it in irb.
Let's look at another piece of code.
Copy codeThe Code is 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 # {}"
Puts "B is # {B }"
The result is:
Copy codeThe Code is as follows:
5 & 3 is 3
5 and 3 is 3
A is 3
B is 5
Is it strange that B is 5 rather than 3.
If you are surprised with these two examples, it means that you have not fully understood the priority of some operators and statements in Ruby, and your judgment is incorrect. Puts {}. class is actually equivalent to (puts {}). class-> nil. class, so the output is empty. {} Is equivalent to an empty block, which is first combined with the method puts. & The priority of and is different, and the priority order of = is compared, & >=> and, so a = 5 & 3 is equivalent to a = (5 & 3), while B = 5 and 3 is equivalent to (B = 5) and 3, therefore, the values of a and B are different.
The following table lists the priorities of common operators and statements in Ruby, which are descending from top to bottom.
Ruby operators (highest to lowest precedence)
Several memory-friendly principles:
1. The priority of keyword classes such as if and is lower than that of symbol classes;
2. The value assignment symbol = | = has a lower priority than the keyword class;
3. [] [] = the element reference has a very high priority.