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?
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.
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(, ).
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With