user2851669 user2851669 -5 years ago 96
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?

Answer Source

You can use join instead of an each loop:

puts "something ahead, #{p.join("\n")}\nsomething behind"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download