Ruby Operators


Ruby supports a rich set of operators, as you'd expect from a modern language. Most operators are actually method calls. For example, a + b is interpreted as a.+(b), where the + method in the object referred to by variable a is called with b as its argument.

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

Ruby Arithmetic Operators:
      puts '======'
      # Arithmetic operators
      puts 3 + 4    # add
      puts 7 - 3    # subtract
      puts 3 * 4    # multiply
      puts 12 / 4   # divide
      puts 12**2    # raise to a power (exponent)
      puts 12 % 7   # modulo (remainder)
      puts '======'
      # When you do integer division in Ruby, any fractional part 
      # in the result will be truncated.
      puts 24 / 2       # no problem
      puts 25 / 2       # uh-oh, truncation
      puts 25.0 / 2     # using a float as at least one operand solves it
      puts 25.0 / 2.0   # same when both operands are floats
      puts '======'
      # Unary operators
      puts +7 + -5
      puts -20 + 32
      puts -20 - +32
      puts 20 * -8
      puts '======'
      # Others
      puts 24.div(2)         # division
      puts (25.0).div(2.0)   # result is integer
      puts 12.modulo(5)      # modulo
      puts 12.modulo(5.0)    # modulo with float
      puts 12.divmod(5)      # return array with quotient, modulus
      puts 12.0.divmod(5.0)  # with float
      puts 12.quo(5)         # return the quotient
      puts 12.remainder(5)   # return the remainder
      puts '======'
      

This will produce following result:

      ======
      7
      4
      12
      3
      144
      5
      ======
      12
      12
      12.5
      12.5
      ======
      2
      12
      -52
      -160
      ======
      12
      12
      2
      2.0
      2
      2
      2
      2.0
      12/5
      2
      ======
      

 

Ruby Comparison Operators:
      # Comparision operators
      puts '======'
      # Test two numbers for equality with ==, eql?, !=, or <=>
      puts 12 == 24/2
      puts 24.eql?(12*2)
      puts 12 == 14
      puts 12 != 14
      puts 12 <=> 12
      puts 12 <=> 10
      puts 12 <=> 14
      puts '======'
      # Test if two numbers are equal, less than, or greater than each other
      puts 12 < 14      #less than
      puts 12 < 12
      puts 12 <= 12     # less than or equal to
      puts 12.0 > 11.9
      puts 12.0 >= 12   # greater than or equal to
      puts '======'
      # the <=> (spaceship operator) returns -1, 0, or 1, 
      # depending on whether the first value is equal to the second (0), 
      # less than the second (-1), or greater than the second (1).
      puts 1 <=> 2
      puts 1 <=> 1
      puts 2 <=> 1
      puts '======'
      # The === test if a value is in a range
      puts (10...14) === 9
      puts (10...14) === 10
      puts (10...14) === 12
      puts (10...14) === 14
      puts (10...14) === 15
      puts '======'
      

This will produce following result:

      ======
      true
      true
      false
      true
      0
      1
      -1
      ======
      true
      false
      true
      true
      true
      ======
      -1
      0
      1
      ======
      false
      true
      true
      false
      false
      ======
      

 

Ruby Assignment Operators:
      # Assignment operators
      puts '======'
      x = 37         # assignment
      puts x += 10   # abbreviated assignment add
      puts x -= 10   # abbreviated assignment subtract
      puts x *= 2    # abbreviated assignment multiply
      puts x /= 2    # abbreviated assignment divide
      puts x %= 5    # abbreviated assignment modulus
      puts x **= 3   # abbreviated assignment exponent
      puts '======'
      

This will produce following result:

      ======
      47
      37
      74
      37
      2
      8
      ======
      

 

Ruby Parallel Assignment:

Ruby also supports the parallel assignment of variables. This enables multiple variables to be initialized with a single line of Ruby code. For example:

      a = 10
      b = 20
      c = 30
      

may be more quickly declared using parallel assignment:

      a, b, c = 10, 20, 30
      

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

      a, b = b, c
      

 

Ruby Bitwise Operators:

Bitwise operator works on bits and perform bit by bit operation.

      # Bitwise operators
      a = 78      #  01001110
      b = 54      #  00110110
      puts (a&b)  #  6
      puts (a|b)  #  126
      puts (a^b)  #  120
      puts (~a)   #  -79
      puts (a<<2) #  312
      puts (a>>2) #  19
      

 

Ruby Logical Operators:
      # Logical operators
      ruby = "nifty"
      programming = "fun"
      
      if ruby == "nifty" && programming == "fun"
        puts "&&"
      end
      
      if ruby == "nifty" and programming == "fun"
        puts "&& and"
      end
      
      a, b, c, d = 1, 2 ,3 , 4
      if a == 1 && b == 2 && c == 3 && d == 4
        puts sum = a + b + c + d
      end
      
      programming = "ruby"
      
      if ruby == "nifty" || programming == "fun"
        puts "||"
      end
      
      if ruby == "nifty" or programming == "fun"
        puts "|| or"
      end
      
      ruby = "awesome"
      if ruby == "nifty" or programming == "fun"
        puts "|| or"
      else
      	puts "sorry!"
      end
      
      if not (ruby == "nifty" || programming == "fun")
      	puts "nothing!"
      end
      
      if !(ruby == "nifty" or programming == "fun")
      	puts "nope!"
      end
      

 

Ruby Ternary operator:

It evaluates an expression and then execute one of the two given statements depending upon the result of the evaluation.

      # Ternary operator
      # result = condition ? true_value : false_value
      toppings = 4
      price = toppings > 3 ? 5.99 : 4.99
      puts price
      
      age = 10
      type = age < 18 ? "child" : "adult"
      puts "You are a " + type
      
      # Or...
      puts "You are a " + (age &ly; 18 ? "child" : "adult")
      
      # Ternary operator alternative
      type = 'child' if age < 18
      type = 'adult' unless age < 18
      puts "You are a " + type
      

 

Ruby Range operators:

Ranges occur everywhere: January to December, 0 to 9, lines 50 through 67, and so on. Ruby supports ranges and allows us to use ranges in a variety of ways:

 

Ranges as Sequences:

The first and perhaps most natural use of ranges is to express a sequence. Sequences have a start point, an end point, and a way to produce successive values in the sequence.

Ruby creates these sequences using the ''..'' and ''...'' range operators. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.

      (1..5)        #==> 1, 2, 3, 4, 5
      (1...5)       #==> 1, 2, 3, 4
      ('a'..'d')    #==> 'a', 'b', 'c', 'd'
      

The sequence 1..100 is held as a Range object containing references to two Fixnum objects. If you need to, you can convert a range to an array using the to_a method. Try following example:

      $, =", "   # Array value separator
      range1 = (1..10).to_a
      range2 = ('bar'..'bat').to_a
      
      puts "#{range1}"
      puts "#{range2}"
      

This will produce following result:

      1, 2, 3, 4, 5, 6, 7, 8, 9, 10
      bar, bas, bat
      

Ranges implement methods that let you iterate over them and test their contents in a variety of ways:

      # Assume a range
      digits = 0..9
      
      puts digits.include?(5)
      ret = digits.min
      puts "Min value is #{ret}"
      
      ret = digits.max
      puts "Max value is #{ret}"
      
      ret = digits.reject {|i| i < 5 }
      puts "Rejected values are #{ret}"
      
      digits.each do |digit|
         puts "In Loop #{digit}"
      end
      

This will produce following result:

      true
      Min value is 0
      Max value is 9
      Rejected values are 5, 6, 7, 8, 9
      In Loop 0
      In Loop 1
      In Loop 2
      In Loop 3
      In Loop 4
      In Loop 5
      In Loop 6
      In Loop 7
      In Loop 8
      In Loop 9
      

 

Ranges as Conditions:

Ranges may also be used as conditional expressions. For example, the following code fragment prints sets of lines from standard input, where the first line in each set contains the word start and the last line the word end.:

      while gets
         print if /start/../end/
      end
      

Ranges can be used in case statements:

      score = 70
      
      result = case score
         when 0..40 then "Fail"
         when 41..60 then "Pass"
         when 61..70 then "Pass with Merit"
         when 71..100 then "Pass with Distinction"
         else "Invalid Score"
      end
      
      puts result
      

This will produce following result:

      Pass with Merit
      

 

Ranges as Intervals:

A final use of the versatile range is as an interval test: seeing if some value falls within the interval represented by the range. This is done using ===, the case equality operator.

      if ((1..10) === 5)
        puts "5 lies in (1..10)"
      end
      
      if (('a'..'j') === 'c')
        puts "c lies in ('a'..'j')"
      end
      
      if (('a'..'j') === 'z')
        puts "z lies in ('a'..'j')"
      end
      

This will produce following result:

      5 lies in (1..10)
      c lies in ('a'..'j')
      

 

Ruby splat operator:

The splat operator in Ruby, allows to switch between parameters and arrays.

It splits a list in a series of parameters, or collects a series of parameters to fill an array.

      puts [1..10].inspect
      puts [*1..10].inspect
      

This will produce following result:

      [1..10]
      [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
      

 

Usage:

      # The split mode :
      pet1, pet2, pet3 = *["duck","dog","cat"]
      puts "#{pet1} - #{pet2} - #{pet3}"
      
      #The collect mode :
      *zoo = pet1, pet2, pet3
      puts zoo.inspect
      
      #The splat operator can be used in a case statement :
      WILD = ['lion','gnu']
      TAME = ['cat','cow']
      animal = 'gnu'
      case animal
      	when *WILD
      	puts 'Run!'
      	when *TAME
      	puts 'Catch!'
      end
      

This will produce following result:

      duck - dog - cat
      ["duck", "dog", "cat"]
      Run!
      

 

We can also use the splat operator to create a Hash object from an array of pairs.

      a = [['planes', 21], ['cars', 36]]
      puts a.class
      h = Hash[*a.flatten]
      puts h.class
      puts h.inspect
      

This will produce following result:

      Array
      Hash
      {"planes"=>21, "cars"=>36}
      

 

Ruby defined? operator:

The defined? operator that takes the form of a method call, is used to determine whether or not the passed expression is defined. It returns nil if its argument (which can be an arbitrary expression) is not defined, otherwise it returns a descriptive string of that argument. If the argument is yield, defined? returns the string "yield" if a code block is associated with the current context.

Usage:

      puts defined? 1            # "expression"
      puts defined? dummy        # nil
      puts defined? printf       # "method"
      puts defined? String       # "constant"
      puts defined? $&           # nil
      puts defined? $_           # "global-variable"
      puts defined? Math::PI     # "constant"
      puts defined?( c = 12 )    # "assignment"
      puts defined? 42.abs       # "method"
      

 

Ruby dot "." and double Colon "::" Operators:

You call a module method by preceding its name with the module's name and aperiod, and you reference a constant using the module name and two colons.

The :: 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: Classes are constants, so you may call a class within a Module like Module::Class

You need just to prefix the :: Const_name with an expression that returns the appropriate class or module object.

If no prefix expression is used, the main Object class is used by default.

Here are two examples:

      MR_COUNT = 0        # constant defined on main Object class
      module Foo
        MR_COUNT = 0
        ::MR_COUNT = 1    # set global count to 1
        MR_COUNT = 2      # set local count to 2
      end
      puts MR_COUNT       # this is the global constant
      puts Foo::MR_COUNT  # this is the local "Foo" constant
      

This will produce following result:

      rubyoperators16.rb:4: warning: already initialized constant MR_COUNT
      rubyoperators16.rb:5: warning: already initialized constant MR_COUNT
      1
      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
      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
      

This will produce following result:

       out there inside one
       inside two
       out there inside two
       inside two out there
      #<Proc:0x02a2f1c0@rubyoperators17.rb:3>
       in there inside two