TheWebs
TheWebs

Reputation: 12933

Printing elements of an array with a comma

I have an array arr = ["test", "test 1", "test 2"]. How would I print test, test 1, test 2.? Note the "." and the "," in the expected output.

I know how to iterate over this by doing:

arr.each do |a|
    puts a
end

but I'm not sure how to get the expected output.

Upvotes: 0

Views: 90

Answers (4)

Arup Rakshit
Arup Rakshit

Reputation: 118299

You can do this way also using Array#* which says :-

Repetition — With a String argument, equivalent to ary.join(str).

arr = ["test", "test 1", "test 2"] 
arr*" ," << "." 
# => "test ,test 1 ,test 2."

Upvotes: 1

Peter Alfvin
Peter Alfvin

Reputation: 29439

puts arr.join(' , ')+'.'

with trailing period.

Upvotes: 1

squiguy
squiguy

Reputation: 33380

You can use Array#join.

puts arr.join(", ") << "."

Upvotes: 2

xdazz
xdazz

Reputation: 160953

Use Array.join

puts arr.join(', ')

Upvotes: 1

Related Questions