Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ruby Operators

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 the variable a is called with b as the argument to the method call.

For each operator (+ - * / % ** & | ^ << >> && ||), there is a corresponding abbreviated assignment operator (+= -= etc.).

Ruby Arithmetic Operators

Assuming the value of variable a is 10 and the value of 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
** Exponentiation - performs exponential calculation a**b will give 10 to the power of 20

Ruby Comparison Operators

Assuming the value of variable a is 10 and the value of variable b is 20, then:

operator Description Example
== Checks whether the values of the two operands are equal; if equal, the condition is true. (a == b) is not true.
!= Checks whether the values of the two operands are equal; if not equal, the condition is 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 is 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 is 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 is 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 is true. (a <= b) is true.
<=> Combined comparison operator. Returns 0 if the first operand is equal to the second, 1 if the first operand is greater than the second, and -1 if the first operand is less than the second. (a <=> b) returns -1.
=== Used to test case equality within the when clause of a 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?**(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?bObj returns false, but a.equal?**aObj returns true.

Ruby Assignment Operators

Assuming the value of variable a is 10 and the value of 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 assigns the value of a + b to c
+= Addition assignment operator, assigns the result of adding the right operand to the left operand c += a is equivalent to c = c + a
-= Subtraction assignment operator, assigns the result of subtracting the right operand from the left operand c -= a is equivalent to c = c - a
*= Multiplication assignment operator, assigns the result of multiplying the right operand by the left operand c *= a is equivalent to c = c * a
/= Division assignment operator, assigns the result of dividing the left operand by the right operand c /= a is equivalent to c = c / a
%= Modulus assignment operator, assigns the modulus of the two operands to the left operand c %= a is equivalent to c = c % a
**= Exponentiation assignment operator, performs exponential calculation and assigns 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 with a single line of Ruby code. For example:

a

=

10

b

=

20

c

=

30

Using parallel assignment, you can declare more quickly:

a

,

b

,

c

=

10

,

20

,

30

Parallel assignment is also useful when swapping the values of two variables:

a

,

b

=

b

,

c

Ruby Bitwise Operators

Bitwise operators act on bits and perform operations bit by bit.

Assume that a = 60 and b = 13. 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
& If present in both operands, the binary AND operator copies a bit to the result. (a & b) will give 12, which is 0000 1100
| If present in either operand, the binary OR operator copies a bit to the result. (a | b) will give 61, which is 0011 1101
^ If a bit is present in one operand but not both, the binary XOR operator copies that bit to the result. (a ^ b) will give 49, which is 0011 0001
~ The binary complement operator is a unary operator with a 'flip' bit effect, that is, 0 becomes 1 and 1 becomes 0. (~a ) will give -61, which is 1100 0011, the 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.

Assuming the value of variable a is 10 and the value of variable b is 20, 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 is called the logical OR operator. If either of the two operands is non-zero, the condition is true. (a or b) is true.
&& is called the logical AND operator. If both operands are non-zero, the condition is true. (a && b) is true.
|| is called the logical OR operator. If either of the two operands is non-zero, the condition is true. (a || b) is true.
! is called the logical NOT operator. It is used to reverse the logical state of its operand. If a condition is true, the logical NOT operator will make it false. !(a && b) is false.
not is called the logical NOT operator. It is used to reverse the logical state of its operand. If a condition is true, the logical NOT operator will make it false. not(a && b) is false.

Ruby Ternary Operators

An operation with more than one operand is called a ternary operator. The first evaluates the truth value of an expression, and then decides which of the following two statements to execute based on that result. The syntax of the conditional operator is as follows:

operator Description Example
? : Conditional expression If the condition is true ? the value is X : otherwise the value is Y

Ruby Range Operators

In Ruby, a sequence range is used to create a series of consecutive values - including the start value, the end value (depending on the case), 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 both the start and end values, while the three-dot form creates a range that includes the start value but not the end value.

operator Description Example
.. Creates a range from the start point to the end point (including the end point) 1..10 creates a range from 1 to 10
... Creates a range from the start point to the end point (excluding the end point) 1...10 creates a range from 1 to 9

Ruby defined? Operator

defined? is a special operator that determines in the form of a method call whether the passed expression is defined. It returns a description string of the expression, or if the expression is undefined, returns nil。

The following are various uses of the defined? operator:

Usage 1

defined

?

variable

True if variable has been initialized

For example:

foo

=

42

defined

?

foo

=> "local-variable"

defined

?

$_

=> "global-variable"

defined

?

bar

=> nil (undefined)

Usage 2

defined

?

method_call

True if the method has been defined

For example:

defined

?

puts

=> "method"

defined

?

puts

(

bar

)

=> nil (here bar is undefined)

defined

?

unpack

=> nil (undefined here)

Usage 3

True if there is a method that can be called by super

defined

?

super

For example:

defined

?

super

=> 'super' (if it can be called)

defined

?

super

=> nil (if it cannot be called)

Usage 4

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 has been passed)

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 a dot. You can reference a constant in a class or module using the class or module name and two colons ::.

:: is a unary operator that allows constants, instance methods, and class methods defined within a class or module to be accessed 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 :: and it will return the appropriate class or module object.

If the expression before :: is a class or module name, the corresponding constant value within that class or module is returned; if there is no prefix expression before ::, the corresponding constant value in the main Object class is returned. .

The following are two examples:

MR_COUNT

=

0

A constant defined on 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'

The 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

Ruby Operator Precedence

The following table lists all operators in order of precedence from highest to lowest.

Method operator Description
Is :: Constant resolution operator
Is [ ] [ ]= Element reference, element set
Is ** Exponent
Is ! ~ + - Not, complement, unary plus, unary minus (the method names of the last two 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 whether the specified symbol is defined
not Logical negation
or and Logical composition

**Note:** operators marked in the method column as Is are actually methods and therefore can be overridden.