tags:

views:

85

answers:

2

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?

+3  A: 

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.

molf
Thank you, this is exactly what I was looking for. I did not know that such a method would be implemented in Rails (and not Ruby) or I would have added a comment that I was using Rails
Veger
The link is broken. And just to really nit-pick, your version has an Oxford comma (the comma between two and three), whereas the OP doesn't.
Andrew Grimm
Thanks, the link has been updated. The delimiters are configurable like I mentioned. I just showed the default.
molf
+2  A: 

Just as a readability hint. You can write

array[0..-2] 

to select all but the last element.

Adrian
Did not know that (I am still new to Ruby), but it is indeed better readable
Veger
We are all learners. Glad I could help.
Adrian