user2851669 user2851669 - 10 months ago 38
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
something behind

How do I get the expected output?


You can use join instead of an each loop:

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