使用Ruby加入名称(','和'和')的优雅方式

Luk*_*ick 1 ruby

如果我有一系列名字:

["Alex Ainsworth", "Bob Brown", "Charles Clarke"]
Run Code Online (Sandbox Code Playgroud)

我想要一个字符串,其中除了最后一个用逗号分隔(最后一个是和):

e.g. "Alex Ainsworth, Bob Brown and Charles Clarke"
Run Code Online (Sandbox Code Playgroud)

有谁知道这样做的优雅方式?

更新:我在这种情况下使用Rails,但我问的是一个让我感兴趣的更通用的问题.

Hoc*_*ock 9

如果您使用的是Rails,则可以使用该to_sentence方法.

%(alex bob charles).to_sentence会给你的alex, bob and charles.

该方法在此处定义: activesupport/lib/active_support/core_ext/array/conversions.rb

  • [链接到当前代码库中的"to_sentence"](https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/array/conversions.rb#L11) (3认同)

zet*_*tic 7

[names.slice(0..-2).join(", "),names.last].join(" and ")
Run Code Online (Sandbox Code Playgroud)