Ruby Operators
Ruby supports a rich set of operators. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method on variable a is invoked, with b as the argument to the method call.
For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding abbreviated assignment operator (+= -= and so on).
Ruby Arithmetic Operators
Assume variable a is 10 and variable b is 20, then:
| Operator | Description | Example |
|---|---|---|
| + | Addition - Adds the operands on both sides of the operator. | a + b will give 30 |
| - | Subtraction - Subtracts the right operand from the left operand. | a - b will give -10 |
| * | Multiplication - Multiplies the operands on both sides of the operator. | a * b will give 200 |
| / | Division - Divides the left operand by the right operand. | b / a will give 2 |
| % | Modulus - Divides the left operand by the right operand and returns the remainder. | b % a will give 0 |
| ** | Exponent - Performs exponentiation. | a**b will give 10 to the 20th power |
Ruby Comparison Operators
Assume variable a is 10 and variable b is 20, then:
| Operator | Description | Example |
|---|---|---|
| == | Checks whether the values of two operands are equal; if so, the condition becomes true. | (a == b) is not true. |
| != | Checks whether the values of two operands are equal; if they are not equal, the condition becomes true. | (a != b) is true. |
| > | Checks whether the value of the left operand is greater than the value of the right operand; if so, the condition becomes true. | (a > b) is not true. |
| < | Checks whether the value of the left operand is less than the value of the right operand; if so, the condition becomes true. | (a < b) is true. |
| >= | Checks whether the value of the left operand is greater than or equal to the value of the right operand; if so, the condition becomes true. | (a >= b) is not true. |
| <= | Checks whether the value of the left operand is less than or equal to the value of the right operand; if so, the condition becomes true. | (a <= b) is true. |
| <=> | Combined comparison operator. Returns 0 if the first operand equals the second operand, 1 if the first operand is greater than the second operand, and -1 if the first operand is less than the second operand. | (a <=> b) returns -1. |
| === | Used to testcaseequality within the when clause of a case statement. | (1...10) === 5 returns true. |
| .eql? | Returns true if the receiver and the argument have the same type and equal values. | 1 == 1.0 returns true, but 1.eql?.eql?(1.0) returns false. |
| equal? | Returns true if the receiver and the argument have the same object id. | If aObj is a copy of bObj, then aObj == bObj returns true, a.equal?.equal? bObj returns false, but a.equal?.equal? aObj returns true. |
Ruby Assignment Operators
Assume variable a is 10 and variable b is 20, then:
| Operator | Description | Example |
|---|---|---|
| = | Simple assignment operator. Assigns the value of the right operand to the left operand. | c = a + b will assign the value of a + b to c. |
| += | Add and assignment operator. Adds the right operand to the left operand and assigns the result to the left operand. | c += a is equivalent to c = c + a. |
| -= | Subtract and assignment operator. Subtracts the right operand from the left operand and assigns the result to the left operand. | c -= a is equivalent to c = c - a. |
| *= | Multiply and assignment operator. Multiplies the right operand by the left operand and assigns the result to the left operand. | c *= a is equivalent to c = c * a. |
| /= | Divide and assignment operator. Divides the left operand by the right operand and assigns the result to the left operand. | c /= a is equivalent to c = c / a. |
| %= | Modulus and assignment operator. Takes the modulus of the two operands and assigns it to the left operand. | c %= a is equivalent to c = c % a. |
| **= | Exponent and assignment operator. Performs exponentiation and assigns the result to the left operand. | c **= a is equivalent to c = c ** a. |
Ruby Parallel Assignment
Ruby also supports parallel assignment of variables. This allows multiple variables to be initialized in a single line of Ruby code. For example:
You can declare faster using parallel assignment:
Parallel assignment is also useful when swapping the values of two variables:
Ruby Bitwise Operators
Bitwise operators operate on bits and perform operations bit by bit.
Assume if a = 60 and b = 13, now 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 |
|---|---|---|
| & | Binary AND operator copies a bit to the result if it exists in both operands. | (a & b) will give 12, which is 0000 1100 |
| | | Binary OR operator copies a bit to the result if it exists in either operand. | (a | b) will give 61, which is 0011 1101 |
| ^ | Binary XOR operator copies a bit to the result if it exists in one of the operands but not both. | (a ^ b) will give 49, which is 0011 0001 |
| ~ | Binary complement operator is a unary operator that has the effect of "flipping" bits, i.e., 0 becomes 1 and 1 becomes 0. | (~a ) will give -61, which is 1100 0011, in two's complement form of a signed binary number. |
| << | Binary left shift operator. The value of the left operand is shifted left by the number of bits specified by the right operand. | a << 2 will give 240, which is 1111 0000 |
| >> | Binary right shift operator. The value of the left operand is shifted right by the number of bits specified by the right operand. | a >> 2 will give 15, which is 0000 1111 |
Ruby Logical Operators
The following table lists the logical operators supported by Ruby.
Assume variable a is 10 and variable b is 20, then:
| Operator | Description | Example |
|---|---|---|
| and | Called the logical AND operator. If both operands are true, the condition becomes true. | (a and b) is true. |
| or | Called the logical OR operator. If either operand is non-zero, the condition becomes true. | (a or b) is true. |
| && | Called the logical AND operator. If both operands are non-zero, the condition becomes true. | (a && b) is true. |
| || | Called the logical OR operator. If either operand is non-zero, the condition becomes true. | (a || b) is true. |
| ! | Called the logical NOT operator. Used to reverse the logical state of an operand. If the condition is true, the logical NOT operator makes it false. | !(a && b) is false. |
| not | Called the logical NOT operator. Used to reverse the logical state of an operand. If the condition is true, the logical NOT operator makes it false. | not(a && b) is false. |
Ruby Ternary Operator
An operator with more than one operand is called the ternary operator. First it evaluates the truth value of an expression, then decides which of the two following statements to execute based on the result. The syntax of the conditional operator is as follows:
| Operator | Description | Example |
|---|---|---|
| ? : | Conditional expression | If condition is true ? then value X : otherwise value Y |
Ruby Range Operators
In Ruby, sequence ranges are used to create a series of consecutive values - containing the start value, the end value (depending on the situation), and the values in between.
In Ruby, these sequences are created using the ".." and "..." range operators. The two-dot form creates a range that includes the start and end values, while the three-dot form creates a range that includes only the start value and does not include the end value.
| Operator | Description | Example |
|---|---|---|
| .. | Creates a range from start point to end point (inclusive of end point) | 1..10 creates a range from 1 to 10 |
| ... | Creates a range from start point to end point (exclusive of end point) | 1...10 creates a range from 1 to 9 |
Ruby defined? Operator
defined? is a special operator that takes the form of a method call to determine whether the passed expression is defined. It returns a description string of the expression, and if the expression is not defined, it returnsnil。
The following are various uses of the defined? operator:
Usage 1
Example:
Usage 2
Example:
Usage 3
Example:
Usage 4
Example:
Ruby Dot Operator "." and Double Colon Operator "::"
You can call a method in a class or module by prefixing the method name with the class or module name and.to call a method in a class or module. You can use the class or module name and two colons::to reference a constant within a class or module.
::is a unary operator that allows you to define constants, instance methods, and class methods inside a class or module, accessible from anywhere outside the class or module.
Remember:In Ruby, classes and methods can also be treated as constants.
You only need to prefix the constant name in the expression with::prefix to return the appropriate class or module object.
If::the expression before the prefix 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, it returns the corresponding constant value in the main Object class.
The following are two examples:
Second example:
Ruby Operator Precedence
The following table lists all operators in order of precedence from highest to lowest.
| Method | Operator | Description |
|---|---|---|
| Yes | :: | Constant resolution operator |
| Yes | [ ] [ ]= | Element reference, element set |
| Yes | ** | Exponentiation |
| Yes | ! ~ + - | Not, complement, unary plus, unary minus (the last two have method names +@ and -@) |
| Yes | * / % | Multiplication, division, modulo |
| Yes | + - | Addition and subtraction |
| Yes | >> << | Bitwise right shift, bitwise left shift |
| Yes | & | Bitwise AND |
| Yes | ^ | | Bitwise XOR, bitwise OR |
| Yes | <= < > >= | Comparison operators |
| Yes | <=> == === != =~ !~ | 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 whether the specified symbol is defined | |
| not | Logical negation | |
| or and | Logical composition |
Note:In the method column, those marked asYesoperators are actually methods, and can therefore be overloaded.
Other extensions