【问题标题】:Rails: automatically add "and" as a view helperRails:自动添加“and”作为视图助手
【发布时间】:2022-01-16 12:29:48
【问题描述】:

我正在寻找类似的功能:

collection([1,2,3]) # '1, 2, and 3.'

我认为函数集合或类似的东西是在 Rails 帮助程序中的某个地方定义的,但我找不到它。

有人能解释一下吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    to_sentence 将完成您所要求的大部分工作:

    [1,2,3].to_sentence # => "1, 2, and 3"

    标点符号需要自己加:

    [1,2,3].to_sentence + "." # => "1, 2, and 3."
    # OR
    "#{[1,2,3].to_sentence}." # => "1, 2, and 3."
    

    如果您希望句子大写(不适用于您的示例),您可以使用.humanize

    ["one", "two", "three"].to_sentence # => "one, two, and three"
    ["one", "two", "three"].to_sentence.humanize # => "One, two, and three"
    

    【讨论】:

      【解决方案2】:

      我想你在找to_sentence

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

      【讨论】:

        猜你喜欢
        • 2020-12-20
        • 2011-07-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-10
        • 2013-07-22
        • 1970-01-01
        相关资源
        最近更新 更多