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!

1
  • might also want to look at the CSV class as a specific use case of writing arrays as comma separated values to a file Commented Sep 13, 2017 at 22:50

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, brilliant! Thank you so much! It works! :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.