用英语连接数组

时间:2012-08-21 02:19:59

标签: ruby arrays string

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

[] #=> ""
["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

1 个答案:

答案 0 :(得分: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,则可以使用language filei18n控制此操作,以避免重复或增加此逻辑的复杂性。