Reputation: 37905
I like to join an array resulting in an 'English list'. For example ['one', 'two', 'three']
should result in 'one, two and three'
.
I wrote this code to achieve it (assuming that the array is not empty, which is not the case in my situation)
if array.length == 1
result = array[0]
else
result = "#{array[0, array.length].join(', ')} and #{array.last}"
end
But I was wondering whether there exists some 'advanced' join method to achieve this behaviour? Or at least some shorter/nicer code?
Upvotes: 18
Views: 3963
Reputation: 27793
Just as a readability hint. You can write
array[0...-1]
to select all but the last element.
Edit, updated the code example with Nick's suggestion.
Upvotes: 8
Reputation: 74945
Such a method doesn't exist in core Ruby.
It has been implemented in Rails' Active Support library, though:
['one', 'two', 'three'].to_sentence
#=> "one, two, and three"
The delimiters are configurable, and it also uses Rails' I18n by default.
If you use ActiveSupport or Rails, this would be the preferred way to do it. If your application is non-Railsy, your implementation seems fine for English-only purposes.
Upvotes: 44