Reputation: 125
How would you take a list and make it into a comma-separated string, with "and" before the last element in the array?
Take something like:
list1 = ['a','b','c']
And turn it into this:
=> "a, b, and c"
I remember ruby had a method for this. I've searched however, and couldn't find it. Thanks for the help.
Upvotes: 12
Views: 4343
Reputation: 7188
Try: [list[0...-1].join(", "), list.last].join(", and ")
.
Edit: Rails has the method you were probably looking for, called to_sentence
.
In case you do not have Rails or do not wish to depend on Rails, open Array
class and include the above method, like:
class Array
def join_all(join_with = ", ", connector = "and", last_comma = false)
return self.to_s if self.empty? || self.size==1
connector = join_with+connector if last_comma
[list[0...-1].join(join_with), list.last].join(connector)
end
end
Upvotes: 20
Reputation: 83680
class Array
def to_sentence
sentence = self[0..-2].join(", ") + ", and " + self[-1].to_s if self.size > 1
sentence ||= self.to_s
end
end
so
[1].to_sentence
#=> "1"
[1,2,3].to_sentence
#=> "1, 2, and 3"
[].to_sentence
#=> ""
And in Rails here is to_sentence method that uses I18n locales as well
Upvotes: 8
Reputation: 7204
Might be a better way, but this would work:
class Array
def to_human_string
arr = Array.new(self)
last = arr.pop
arr.join(", ") + ", and " + last.to_s
end
end
Usage:
['a','b','c'].to_human_string
=> "a, b, and c"
You could add options for the delimiter, the 'and' and the optional oxford comma.
Upvotes: 0