Ruby: Loop Thru List

By Xah Lee. Date:

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
end

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
  |kk,vv|
  p kk, vv # print key and value
end

=begin
prints

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

=end

If you have a question, put $5 at patreon and message me.

  1. Ruby Basics
  2. Doc Lookup
  3. Print Version String
  4. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?

  1. Unicode 💎
  2. Quote String
  3. Quote Long String
  4. Format String
  5. String Operations
  6. True, False
  7. “if then else”
  8. for, while, Loop
  9. List
  10. Loop Thru List
  11. Hash Table
  12. Function Optional Parameter
  13. Map f to List
  14. Complex Numbers
  1. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  2. Predefined Global Variables