开发者

Elegant way of joining names (',' and 'and') with Ruby [duplicate]

This question already has answers here: Create a human-readable list with "and" inserted before the last element from a ruby list (3 answers) Closed 9 years ago.

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 ")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜