How to "convert" an array to a sentence?

I am using Ruby on Rails v3.0.9, and I would like to "convert" an array of strings to 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 this?

+6
source share
2 answers

Rails has an Array#to_sentence , which will do the same as array.join(', ') , and optionally add "and" to the last element.

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

The rest, as you can see, simply unites it.

+6
source
Answer to

@coreyward is close, but its conclusion of sentences does not match the requested result. This will give you exactly what you want:

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

See the docs for more details on examples and options.

+1
source

Source: https://habr.com/ru/post/895552/


All Articles