user2851669 user2851669 - 5 months ago 9
Ruby Question

Loop an array inside puts statement in Ruby

I am looping an array inside puts statement.

p = ["1", "2", "3"]
puts "something ahead, #{p.each {|t| puts "#{t}\n"}} something behind"


Output -
something ahead, ["1", "2", "3"] something behind


Expected output -

something ahead, 1
2
3
something behind


How do I get the expected output?

Answer

You can use join instead of an each loop:

puts "something ahead, #{p.join("\n")}\nsomething behind"
Comments