简体   繁体   English

Ruby-单词数组中类似英语的句子列表

[英]Ruby - English sentence-like list from an array of words

Is there a Ruby/Rails "magic" helper to go from an array of words, like 是否有Ruby / Rails的“魔术”助手可以从一系列单词中找到,例如

["Sugar", "Water", "Lemons", "Tea"]

to a single string which can fit in a sentence: 可以适合句子的单个字符串:

"Sugar, Water, Lemons and Tea"

I know about array.join() , but the "and" before the last entry is important. 我知道array.join() ,但是最后一个条目之前的“和”很重要。
I am just asking because I know Ruby and Rails have a lot of helpful methods lurking in the dark and I want to keep my code as clean as possible 我之所以问是因为我知道Ruby和Rails有很多有用的方法在黑暗中潜伏,所以我想保持代码尽可能整洁

Seems like this is what you're looking for :) 似乎这就是您要寻找的:)

http://apidock.com/rails/Array/to_sentence http://apidock.com/rails/Array/to_sentence

to_sentence(options = {})

"Converts the array to a comma-separated sentence where the last element is joined by the connector word." “将数组转换为逗号分隔的句子,其中最后一个元素由连接器词连接。”

Example: 例:

["Sugar", "Water", "Lemons", "Tea"].to_sentence # => "Sugar, Water, Lemons, and Tea"

You can also pass options, like what should be your last word connector: 您还可以传递选项,例如您的最后一个单词连接器:

["Sugar", "Water", "Lemons", "Tea"].to_sentence(last_word_connector: ' or ') # => "Sugar, Water, Lemons or Tea"

EDIT: 编辑:

As pointed out by Max Williams, this will by default leave a comma next to the last word. 正如Max Williams所指出的,默认情况下,这将在最后一个单词旁边留下一个逗号。 To avoid that, you can explicitly declare " and " as your last word connector, as the default seems to be ", and " 为避免这种情况,您可以显式声明" and "作为您的最后一个单词连接器,因为默认值似乎是", and "

["Sugar", "Water", "Lemons", "Tea"].to_sentence(last_word_connector: ' and ') # => "Sugar, Water, Lemons and Tea"

try this 尝试这个

pry(main)> ["Sugar", "Water", "Lemons", "Tea"].to_sentence
=> "Sugar, Water, Lemons, and Tea"

or 要么

 pry(main)> ["Sugar", "Water", "Lemons", "Tea"].to_sentence(words_connector: ', ', last_word_connector: ' and ')
  => "Sugar, Water, Lemons and Tea"

You can still use join, just do the last element separately. 您仍然可以使用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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM