Each

suggest change

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 Ruby way to solve this. Let’s break it down.

  1. (1..10) is a range from 1 through 10. To exclude 10, write (1...10).
  2. .each calls the block once for each element. Here, that is each number in the range.
  3. { |i| puts i.even? ? 'even' : 'odd' } is the block.

Inside the block:

  1. |i| binds each element to i.
  2. puts prints a value and then a newline. Use print if you do not want the newline.
  3. i.even? is true when i is even. i % 2 == 0 also works; the built-in method is clearer.
  4. ? 'even' : 'odd' is Ruby’s ternary operator. expression ? a : b is short for:
if expression
  a
else
  b
end

For more than one line, pass 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"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents