YouTip LogoYouTip

Ruby Operator

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

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

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

Assume variable a has value 10 and variable b has value 20, then:

Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (a == b) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
<= Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a <= b) is true.
<=> Combined comparison operator. Returns 0 if the first operand equals 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.
=== Tests equality within the when clause of a case statement. (1...10) === 5 returns true.
.eql? Returns true if the receiver and 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 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.

Assume variable a has value 10 and variable b has value 20, then:

Operator Description Example
= Simple assignment operator, assigns the value from the right side operand to the left side operand c = a + b assigns 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 with 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 with the right operand and assigns the result to the left operand c /= a is equivalent to c = c / a
%= Modulus AND assignment operator, takes modulus using two operands and assigns the result to the left operand c %= a is equivalent to c = c % a
**= Exponent AND assignment operator, performs exponential calculation 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 enables multiple variables to be initialized by a single line of Ruby code. For example:

a = 10
b = 20
c = 30

Using parallel assignment can be more quickly declared as:

a, b, c = 10, 20, 30

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

a, b = b, c

Bitwise operators work on bits and perform bit-by-bit operation. Assume if a = 60, and b = 13, now in binary format, they will be 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 if it exists in either operand. (a | b) will give 61, which is 0011 1101
^ Binary XOR Operator copies the bit if it is set in one operand but not both. (a ^ b) will give 49, which is 0011 0001
~ Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~a ) will give -61, which is 1100 0011 in 2's complement form, a signed binary number.
<< Binary Left Shift Operator. The left operand's value is moved 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 left operand's value is moved right by the number of bits specified by the right operand. a >> 2 will give 15, which is 0000 1111

The following table lists the logical operators supported by Ruby.

Assume variable a has value 10 and variable b has value 20, then:

Operator Description Example
and Called Logical AND operator. If both the operands are true, then condition becomes true. (a and b) is true.
or Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (a or b) is true.
&& Called Logical AND operator. If both the operands are non zero, then condition becomes true. (a && b) is true.
|| Called Logical OR Operator. If any of the two operands are non zero then condition becomes true. (a || b) is true.
! Called Logical NOT Operator. Used to reverse the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(a && b) is false.
not Called Logical NOT Operator. Used to reverse the logical state of its operand. If a condition is true then Logical NOT operator will make false. not(a && b) is false.

An operation having three operands is called a ternary operator. First evaluates a truthy or falsy value, then depending on the result, decides which of the two statements to execute. The syntax for the conditional operator is:

Operator Description Example
? : Conditional Expression If Condition is true ? Then value X : Otherwise value Y

In Ruby, sequence ranges are used to create a series of values - starting value, ending 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 an inclusive range, while the three-dot form creates an exclusive range.

Operator Description Example
.. Creates a range from start point to end point (inclusive) 1..10 Creates a range from 1 to 10
... Creates a range from start point to end point (exclusive) 1...10 Creates a range from 1 to 9

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, or nil if the expression is not defined.

Here are the various usages of the defined? operator:

Usage 1

defined? variable

For example:

foo = 42
defined? foo     # => "local-variable"
defined? $_      # => "global-variable"
defined? bar     # => nil

Usage 2

defined? method_call

For example:

defined? puts        # => "method"
defined? puts(bar)   # => nil
defined? unpack      # => nil

Usage 3

defined? super

For example:

defined? super    # => "super"
defined? super    # => nil (if the method calling it doesn't exist)

Usage 4

defined? yield

For example:

defined? yield    # => "yield" (if there is a block passed)
defined? yield    # => nil (if there is no block passed)

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 by prefixing the constant name with the class or module name and two colons ::.

:: is a unary operator that allows for 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 be treated as constants.

You just need to prefix the constant name in the expression with the :: prefix, which returns the appropriate class or module object.

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

Here are two examples:

MR_COUNT = 0         # constant defined on main Object class
module Foo
  MR_COUNT = 0       # constant defined in Foo module
  ::MR_COUNT = 1     # constant defined on main Object class
  MR_COUNT = 2       # constant redefined in Foo module
end

puts MR_COUNT        # => 0
puts Foo::MR_COUNT   # => 2

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  # => " out there inside one"
puts Inside_two.new.where_is_my_CONST  # => " inside two"
puts Object::CONST + Inside_two::CONST # => " out there inside two"
puts Inside_two::CONST + CONST         # => " inside two out there"
puts Inside_one::CONST                 # => #<Proc:0x...>
puts Inside_one::CONST.call + Inside_two::CONST # => " in there inside two"

The following table lists all the Ruby 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 and minus (method names for the last two are +@ and -@)
Yes * / % Multiplication, division, modulus
Yes + - Addition and subtraction
Yes >> << Right and left bitwise shift
Yes & Bitwise AND
Yes ^ | Bitwise exclusive OR and regular OR
Yes <= < > >= Comparison operators
Yes <=> == === != =~ !~ Equality and pattern matching operators (!= and !~ cannot be defined as methods)
&& Logical AND
|| Logical OR
.. ... Range (inclusive and exclusive)
?: Ternary if-then-else
= %= { /= -= += |= &= >>= <<= *= &&= ||= **= Assignment
defined? Check if specified symbol is defined
not Logical negation
or and Logical composition

Note: Operators marked as Yes in the Method column are actually methods, and therefore can be overridden.

← Ruby CommentRuby Variable β†’