Ruby Language Each


Example

Ruby has many types of enumerators but the first and most simple type of enumerator to start with is each. We will print out even or odd for each number between 1 and 10 to show how each works.

Basically there are two ways to pass so called blocks. A block is a piece of code being passed which will be executed by the method which is called. The each method takes a block which it calls for every element of the collection of objects it was called on.

There are two ways to pass a block to a method:

Method 1: Inline

(1..10).each { |i| puts i.even? ? 'even' : 'odd' }

This is a very compressed and ruby way to solve this. Let's break this down piece by piece.

  1. (1..10) is a range from 1 to 10 inclusive. If we wanted it to be 1 to 10 exclusive, we would write (1...10).
  2. .each is an enumerator that enumerates over each element in the object it is acting on. In this case, it acts on each number in the range.
  3. { |i| puts i.even? ? 'even' : 'odd' } is the block for the each statement, which itself can be broken down further.
    1. |i| this means that each element in the range is represented within the block by the identifier i.
    2. puts is an output method in Ruby that has an automatic line break after each time it prints. (We can use print if we don't want the automatic line break)
    3. i.even? checks if i is even. We could have also used i % 2 == 0; however, it is preferable to use built in methods.
    4. ? "even" : "odd" this is ruby's ternary operator. The way a ternary operator is constructed is expression ? a : b. This is short for
    if expression
      a
    else
      b
    end
    

For code longer than one line the block should be passed as a multiline block.

Method 2: Multiline

(1..10).each do |i|
  if i.even?
    puts 'even'
  else
    puts 'odd'
  end
end

In a multiline block the do replaces the opening bracket and end replaces the closing bracket from the inline style.

Ruby supports reverse_each as well. It will iterate the array backwards.

@arr = [1,2,3,4]
puts @arr.inspect # output is [1,2,3,4]

print "Reversed array elements["
@arr.reverse_each do |val|
        print " #{val} " # output is 4 3 2 1
end
print "]\n"