Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join array contents into an 'English list'

Tags:

arrays

ruby

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?

like image 485
Veger Avatar asked Jan 10 '10 21:01

Veger


People also ask

How do you join elements in an array?

Array.prototype.join() The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Which of the following joins all elements of an array into a string?

join() method is used to join the elements of an array into a string. The elements of the string will be separated by a specified separator and its default value is a comma(, ).

What is SQL array join?

This is the function to use if you want to concatenate all the values in an array field into one string value. You can specify an optional argument as a separator, and it can be any string. If you do not specify a separator, there will be nothing aded between the values.


1 Answers

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.

like image 157
molf Avatar answered Oct 04 '22 10:10

molf