Return value of a for loop in Ruby

I understand that, in Ruby, a for loop is an expression and therefore has a value which can be assigned to a variable. For example

x = for i in 0..3 do

sets x to 0..3 – the range over which the loop iterates.

Is the return value of a for loop always the range as above, or can it differ depending on the body of the loop?


What is returned by the for loop is dependent on how the enumerator you are looping over is implemented. For example, let’s implement our own enumerator.

chipmunks = { |c|
    c << "Alvin"
    c << "Simon"
    c << "Theodore"

Notice that the last thing in the Enumerator is the string “Dave”. Now let’s use this in a .each loop.

result = chipmunk.each do |chipmunk|
    puts chipmunk
#=> Alvin
#=> Simon
#=> Theodore

puts result
#=> Dave

My guess is that Range is implemented in such a way that its enumerator returns itself. By doing so, it gives you the ability to chain methods.

(1..100).each { |n| something(n) }.each {|y| something_else(y) }

Leave a Reply

Your email address will not be published. Required fields are marked *