3

是否有现成的库/方法可以将数组序列化为字符串,如下所示?

[] #=> ""
["Peter"] #=> "Peter"
["Peter", "Paul"] #=> "Peter and Paul"
["Peter", "Paul", "Mary"] #=> "Peter, Paul, and Mary" (with Oxford comma)
["Peter", "Paul", "Mary"] #=> "Peter, Paul and Mary" (without Oxford comma)

如果不是,那么最短的方法是什么?我想要这种形式:

class Array
    def conjoin oxford_comma = true
        ...
    end
end
4

1 回答 1

5

是的。

require 'active_support/core_ext/array/conversions'

["Peter", "Paul", "Mary"].to_sentence
=> "Peter, Paul, and Mary"

或没有牛津逗号。

["Peter", "Paul", "Mary"].to_sentence(:last_word_connector => ' and ')
=> "Peter, Paul and Mary" 

这是来自apidock的更多信息

另请注意,如果您使用 Rails,至少,您可以使用i18n从语言文件中控制它,以避免重复或增加此逻辑的复杂性。

于 2012-08-21T02:37:14.673 回答