1

how to write an array in Ruby keeping the elements of the array itself in the same line?

E.g.

a= ["Tom", "Jerry"]
puts a

gives:

Tom
Jerry

But I need to have:

Tom, Jerry

Thank you for your help!

  • might also want to look at the [`CSV`](https://ruby-doc.org/stdlib-2.4.0/libdoc/csv/rdoc/CSV.html) class as a specific use case of writing arrays as comma separated values to a file – Simple Lime Sep 13 '17 at 22:50

1 Answers1

4

You can use the join method on the array to do this.

a= ["Tom", "Jerry"]
puts a.join(", ")

Interestingly, you can also multiply the array by the string you wish to separate the elements by:

a= ["Tom", "Jerry"]
puts a * ", "

Both of the above give the same output:

Tom, Jerry
Chad
  • 18,706
  • 4
  • 46
  • 63