English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Ruby supports a rich set of operators. Most operators are method calls. For example, a + b is interpreted as a.+(b), which points to the variable a's + The method is called, and b is the parameter of the method call.
For each operator (+ - * / % ** & | ^ << >> && ||), each has a corresponding abbreviated assignment operator (+= -= etc.).
Assuming the value of variable a is 10The value of variable b is 2If 0, then:
Operator | Description | Example |
---|---|---|
+ | Addition - Add the operands on both sides of the operator | a + b will get 30 |
- | Subtraction - Subtracts the right operand from the left operand | a - b will get -10 |
* | Multiplication - Multiplies the operands on both sides of the operator | a * b will get 200 |
/ | Division - Divides the left operand by the right operand | b / a will get 2 |
% | Modulus - Divides the left operand by the right operand, returns the remainder | b % a will get 0 |
** | Exponentiation - to perform exponential calculation | a**b will get 10 of 20 to the power |
Assuming the value of variable a is 10The value of variable b is 2If 0, then:
Operator | Description | Example |
---|---|---|
== | Check if the values of the two operands are equal, if equal, then the condition is true. | (a == b) is not true. |
!= | Check if the values of the two operands are equal, if not equal, then the condition is true. | (a != b) is true. |
> | Check if the value of the left operand is greater than the value of the right operand, if so, the condition is true. | (a > b) is not true. |
< | Check if the value of the left operand is less than the value of the right operand, if so, the condition is true. | (a < b) is true. |
>= | Check if the value of the left operand is greater than or equal to the value of the right operand, if so, the condition is true. | (a >= b) is not true. |
<= | Check if the value of the left operand is less than or equal to the value of the right operand, if so, the condition is true. | (a <= b) is true. |
<=> | Combined comparison operator. If the first operand is equal to the second operand, then return 0; if the first operand is greater than the second operand, then return 1, if the first operand is less than the second operand, then return -1. | (a <=> b) returns -1. |
=== | is used for testing case Equality within the when clause of a statement. | (1...10) === 5 Returns true. |
.eql? | Returns true if the receiver and the parameters have the same type and equal values. | 1 == 1.0 returns true, but 1.eql?(1.0) returns false. |
equal? | If the receiver and the parameters have the same object id, then return true. | If aObj is a copy of bObj, then aObj == bObj returns true, a.equal?bObj returns false, but a.equal?aObj returns true. |
Assuming the value of variable a is 10The value of variable b is 2If 0, then:
Operator | Description | Example |
---|---|---|
= | Simple assignment operator, assigns the value of the right operand to the left operand | c = a + b will assign a + The value of b is assigned to c |
+= | Addition and assignment operator, assigns the result of adding the right operand to the left operand to the left operand | c += a is equivalent to c = c + a |
-= | Subtraction and assignment operator, assigns the result of subtracting the right operand from the left operand to the left operand | c -= a is equivalent to c = c - a |
*= | Multiplication and assignment operator, assigns the result of multiplying the right operand by the left operand to the left operand | c *= a is equivalent to c = c * a |
/= | Division and assignment operator, assigns the result of dividing the left operand by the right operand to the left operand | c /= a is equivalent to c = c / a |
%= | Modulo and assignment operator, assigns the modulus of two operands to the left operand | c %= a is equivalent to c = c % a |
**= | The exponentiation and assignment operator, which performs exponentiation and assigns the result to the left operand. | c **= a is equivalent to c = c ** a |
Ruby also supports parallel assignment of variables. This allows multiple variables to be initialized through a single line of Ruby code. For example:
a = 10 b = 20 c = 30
Using parallel assignment can declare more quickly:
a, b, c = 10, 20, 30
Parallel assignment is also very useful when swapping the values of two variables:
a, b = b, c
Bitwise operators operate on bits and perform operations bit by bit.
Assuming if a = 60, and b = 13Now, in binary format, they are as follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
The following table lists the bitwise operators supported by Ruby.
Operator | Description | Example |
---|---|---|
& | The binary AND operator copies a bit to the result if it exists in both operands. | (a & b) will result in 12which is 0000 1100 |
| | The binary OR operator copies a bit to the result if it exists in any of the operands. | (a | b) will result in 61which is 0011 1101 |
^ | The binary XOR operator copies a bit to the result if it exists in one of the operands but not in both. | (a ^ b) will result in 49which is 0011 0001 |
~ | The binary complement operator is a unary operator with a "flip" bit effect, meaning 0 becomes1,1becoming 0. | (~a) will result in -61which is 1100 0011which is the two's complement form of a signed binary number. |
<< | The binary left shift operator. The value of the left operand is shifted to the left by the number of bits specified by the right operand. | a << 2 The result will be 240, which is 1111 0000 |
>> | The binary right shift operator. The value of the left operand is shifted to the right by the number of bits specified by the right operand. | a >> 2 The result will be 15which is 0000 1111 |
The following table lists the logical operators supported by Ruby.
Assuming the value of variable a is 10The value of variable b is 2If 0, then:
Operator | Description | Example |
---|---|---|
and | Called the logical AND operator. If both operands are true, the condition is true. | (a and b) is true. |
or | Called the logical OR operator. If either of the operands is non-zero, the condition is true. | (a or b) is true. |
&& | Called the logical AND operator. If both operands are non-zero, the condition is true. | (a && b) is true. |
|| | Called the logical OR operator. If either of the operands is non-zero, the condition is true. | (a || b) is true. |
! | Called the logical NOT operator. It reverses the logical state of the operand. If the condition is true, the logical NOT operator will make it false. | !(a && b) is false. |
not | Called the logical NOT operator. It reverses the logical state of the operand. If the condition is true, the logical NOT operator will make it false. | not(a && b) is false. |
Having more than one operation is called a ternary operator. The first expression calculates the true or false value of the expression, and then decides which of the two statements to execute next based on this result. The syntax of the conditional operator is as follows:
Operator | Description | Example |
---|---|---|
? : | Conditional expression | If the condition is true ? then the value is X : otherwise the value is Y |
In Ruby, sequence ranges are used to create a series of consecutive values - Including the starting value, ending value (depending on the situation), and the values between them.
In Ruby, these sequences are created using the range operators ".." and "...". The range created with two dots includes both the starting and ending values, while the range created with three dots includes only the starting value and does not include the ending value.
Operator | Description | Example |
---|---|---|
.. | Create a range from the starting point to the ending point (including the ending point) | 1..10 Create a range from 1 to 10 range |
... | Create a range from the starting point to the ending point (excluding the ending point) | 1...10 Create a range from 1 to 9 range |
defined? is a special operator that uses the form of a method call to determine if the passed expression is defined. It returns the description string of the expression, and returns nil.
Below are various usages of the defined? operator:
defined? variable # => True if variable has been initialized
For example:
foo = 42 defined? foo # => "local"-variable" defined? $_ # => "global"-variable" defined? bar # => nil (undefined)
defined? method_call # => True if the method has been defined
For example:
defined? puts # => "method" defined? puts(bar) # => nil (bar is not defined here) defined? unpack # => nil (not defined here)
# => True if there is a method that can be called with super defined? super
For example:
defined? super # => "super" (if it can be called) defined? super # => nil (if it cannot be called)
defined? yield # => True if a block has been passed
For example:
defined? yield # => "yield" (if a block has been passed) defined? yield # => nil (if no block is passed)
You can call methods within a class or module by adding the class or module name and . to the method name. You can reference constants within a class or module using the class or module name and two colons ::.
:: is a unary operator that allows constants, examples, and class methods to be defined within classes or modules, and can be accessed from anywhere outside the class or module.
Remember:In Ruby, classes and methods can also be used as constants.
You just need to add the constant name before the expression. :: Prefix, you can return the appropriate class or module object.
If the expression before :: is a class or module name, it returns the corresponding constant value within that class or module; if there is no prefix expression before ::, it returns the corresponding constant value in the main Object class. .
Here are two examples:
MR_COUNT = 0 # Defined in the main Object class module Foo MR_COUNT = 0 ::MR_COUNT = 1 # Set the global count to 1 MR_COUNT = 2 # Set the local count to 2 end puts MR_COUNT # This is the global constant puts Foo::MR_COUNT # This is the local constant of 'Foo'
Second example:
CONST = 'out there' class Inside_one CONST = proc {'in there'} def where_is_my_CONST ::CONST + 'inside one' end end class Inside_two CONST = 'inside two' def where_is_my_CONST CONST end end puts Inside_one.new.where_is_my_CONST puts Inside_two.new.where_is_my_CONST puts Object::CONST + Inside_two::CONST puts Inside_two::CONST + CONST puts Inside_one::CONST puts Inside_one::CONST.call + Inside_two::CONST
The following table lists all operators in order of precedence from high to low.
Method | Operator | Description |
---|---|---|
is | :: | Constant parsing operator |
is | [ ] [ ]= | Element Reference, Element Collection |
is | ** | Exponentiation |
is | ! ~ + - | Negation, Complement, Unary Addition, Unary Subtraction (the names of the last two methods are +@ and -@) |
is | * / % | Multiplication, Division, Modulus |
is | + - | Addition and Subtraction |
is | >> << | Bitwise Right Shift, Bitwise Left Shift |
is | & | Bitwise AND |
is | ^ | | Bitwise XOR, Bitwise OR |
is | <= < > >= | Comparison Operators |
is | <=> == === != =~ !~ | Equality and Pattern Matching Operators (!= and !~ cannot be defined as methods) |
&& | Logical AND | |
|| | Logical OR | |
.. ... | Range (inclusive, exclusive) | |
? : | Ternary if-then-else | |
= %= { /= -= += |= &= >>= <<= *= &&= ||= **= | Assignment | |
defined? | Check if the specified symbol is defined | |
not | Logical Negation | |
or and | Logical Composition |
Note:The method list is marked as is The operators are actually methods, so they can be overloaded.