Search code examples
rubyiterationeachputs

Why the Ruby each iterator goes first in the execution?


I've came across a weird thing doing simple tasks in Ruby. I just want to iterate the alphabet with the each method but the iteration goes first in the execution:

alfawit = ("a".."z")
puts "That's an alphabet: \n\n #{ alfawit.each { |litera| puts litera } } "

and this code results in this: (abbreviated)

a
b
c
⋮
x
y
z
That's an alphabet: 

 a..z 

Any ideas why it works like this or what supposedly I did wrong?

Thanks in advance.


Solution

  • Because your each call is interpolated in your string literal that's executed before the fixed string. Also, each returns an Enumerable, in fact you print even that. Try this one

    alfawit = ("a".."z")
    puts "That's an alphabet: \n\n"
    alfawit.each { |litera| puts litera } 
    

    or

    puts "That's an alphabet: \n\n"
    ("a".."z").each { |litera| puts litera } 
    

    you can use interpolation if you want but in this way

    alfawit = ("a".."z")
    puts "That's an alphabet: \n\n#{alfawit.to_a.join("\n")}"