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. Unicode 💎
  5. Quote String
  6. Quote Long String
  7. Format String
  8. String Operations
  9. True, False
  10. “if then else”
  11. for, while, Loop
  12. List
  13. Loop Thru List
  14. Hash Table
  15. Function Optional Parameter
  16. Map f to List
  17. Complex Numbers
  18. Intro to Reading Ruby Doc: What's M, C, ::, # ?
  19. Predefined Global Variables
  20. What's RVM, Gem, Rake, Bundler, RDoc, ri, irb?