Return value of a for loop in Ruby Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Return value of a for loop in Ruby without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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) }
We are here to answer your question about Return value of a for loop in Ruby - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji