How to "transform" an array in a sentence?
Asked Answered
C

2

9

I am using Ruby on Rails v3.0.9 and I would like to "transform" an array of strings in a sentence including punctuation. That is, if I have an array like the following:

["element 1", "element 2", "element 3"]

I would like to get\build:

# Note: I added 'Elements are: ' at the begin, ',' between elements and '.' at
# the end.
"Elements are: element 1, element 2, element 3."

How can I do that?

Counterclaim answered 21/8, 2011 at 23:50 Comment(0)
A
9

Rails has Array#to_sentence that will do the same as array.join(', ') and additionally add "and " before the last item.

puts "Elements are: #{["element 1", "element 2", "element 3"].to_sentence}."

The rest, as you can see, is just putting it together.

Aphra answered 21/8, 2011 at 23:51 Comment(1)
@Counterclaim this is probably what you want, but if you want exact same sentence as you created, replace to_sentence with join(", ")Kalinin
M
1

@coreyward's answer is close, but his suggestion's output doesn't match the requested output. This will give you exactly what you want:

puts "Elements are: #{array.to_sentence(last_word_connector: ', ')}."

See the docs for more examples and options.

Magic answered 20/1, 2016 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.