Ruby: Loop Thru List


Loop thru a list.

# -*- coding: utf-8 -*-
# ruby

aa = ['one', 'two', 'three', 'infinity']

# loop thru a list
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 xx

In the above, the “each” is a method for list 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 list, get both index and value.

# -*- coding: utf-8 -*-
# ruby

aa = ['one', 'two', 'three', 'infinity']

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

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

# -*- coding: utf-8 -*-
# ruby

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

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



blog comments powered by Disqus