是否有一个Ruby / Rails“魔术”助手来自一系列单词,比如
["Sugar", "Water", "Lemons", "Tea"]
到一个可以放在句子中的单个字符串:
"Sugar, Water, Lemons and Tea"
我知道array.join()
,但最后一个条目前的“和”很重要
我只是问,因为我知道Ruby和Rails有很多有用的方法潜伏在黑暗中我想尽可能保持我的代码干净
答案 0 :(得分:10)
似乎这就是你正在寻找的东西:)
http://apidock.com/rails/Array/to_sentence
to_sentence(options = {})
"将数组转换为逗号分隔的句子,其中最后一个元素由连接词加入。"
示例:
["Sugar", "Water", "Lemons", "Tea"].to_sentence # => "Sugar, Water, Lemons, and Tea"
你也可以传递选项,比如你的最后一个连接词:
["Sugar", "Water", "Lemons", "Tea"].to_sentence(last_word_connector: ' or ') # => "Sugar, Water, Lemons or Tea"
编辑:
正如Max Williams指出的那样,默认情况下会在最后一个单词旁边留下逗号。为避免这种情况,您可以明确声明" and "
为最后一个单词连接符,因为默认值为", and "
["Sugar", "Water", "Lemons", "Tea"].to_sentence(last_word_connector: ' and ') # => "Sugar, Water, Lemons and Tea"
答案 1 :(得分:4)
试试这个
pry(main)> ["Sugar", "Water", "Lemons", "Tea"].to_sentence
=> "Sugar, Water, Lemons, and Tea"
或
pry(main)> ["Sugar", "Water", "Lemons", "Tea"].to_sentence(words_connector: ', ', last_word_connector: ' and ')
=> "Sugar, Water, Lemons and Tea"
答案 2 :(得分:0)
您仍然可以使用join,只需单独执行最后一个元素。
def commas_with_and(arr)
arr[0..-2].join(", ") << " and " << arr[-1]
end
arr = ["Sugar", "Water", "Lemons", "Tea"]
commas_with_and(arr)
>> "Sugar, Water, Lemons and Tea"