Ruby: Loop thru Array

By Xah Lee. Date: . Last updated: .

Loop thru a array.

# ruby

aa = [1,2,3]

# loop thru array
aa.each { # opening curly bracket must be on this line, else syntax error.
  |xx| # each element is set to a dummy variable xx
  p xx
}

# prints 1 2 3

In the above, the “each” is a method for array object. This method takes a “block” argument in the form of { … }.

A Ruby “block” typically has the form { |var| … } OR do |var| … end, where the var is a dummy variable. Ruby's “block” is similar to lambda (aka anonymous function).

When a method takes a “block”, you can think of it as taking a pure function written in the form { |var| body }.

Loop thru a array, get both index and value.

# ruby

aa = ["a", "b", "c"]

# loop thru a array and gets its value and index
aa.each_with_index do
  |vv, ii| # first item is value
  p vv, ii # print value and index
end

The following construct loops thru a dictionary, each time assigning both keys and values to variables.

# ruby

hh = { :john => 3, :mary => 4, :joe => 5, :vicky => 7}

# loop thru a hash, and get key and value
hh.each do
  |kk,vv|
  p kk, vv # print key and value
end

=begin
prints

:john
3
:mary
4
:joe
5
:vicky
7

=end

Ruby Tutorial

Print

String

Types

Variable

Boolean

Branching

Loop, Iteration

Data Structure

Function

Misc