Elegant way of joining names (',' and 'and') with Ruby [duplicate]
If I have an array of names:
["Alex Ainsworth", "Bob Brown", "Charles Clarke"]
And I want a string where all but the last is separated with a comma (with the last be开发者_高级运维ing an and):
e.g. "Alex Ainsworth, Bob Brown and Charles Clarke"
Does anyone know an elegant way of doing this?
Update: I am using Rails in this case, but I was asking a more generic question that interested me.
If you are using Rails, you could use the to_sentence
method.
%(alex bob charles).to_sentence
would give you alex, bob and charles
.
That method is defined here: activesupport/lib/active_support/core_ext/array/conversions.rb
[names.slice(0..-2).join(", "),names.last].join(" and ")
精彩评论