【问题标题】:rails singularize to a / anrails 单数化为 a / an
【发布时间】:2012-01-01 21:53:22
【问题描述】:

有没有一种类似于单数化的方法来根据单词添加“a”或“an”?

  • 喜欢f(apple) # => 一个苹果
  • f(carpet) #=> 地毯

【问题讨论】:

    标签: ruby-on-rails-3 pluralize singular


    【解决方案1】:

    看这里http://deveiate.org/projects/Linguistics/wiki/English,看看这个question

    如果您需要一些更简单的东西,例如,如果单词以元音开头,则在前面加上“an”,您可以使用我的一个衬里:

    String.class_eval { def prepend; %w(a e i o u).include?(downcase.first) ? "an #{self}" : "a #{self}"; end }
    

    将其放入应用程序的config/initializers 文件夹中的prepend.rb 文件中。

    然后你就可以使用了

    "carrot".prepend => "a carrot"
    "apple".prepend => "an apple"
    

    【讨论】:

    • 我喜欢。我会谦虚地建议使用 a_or_an 作为名称。 prepend 非常通用,但可能太多了。对于普通的代码读者来说,carrot.a_or_an 会很清楚 :) 如果我们在谈论其他东西,比如“这个”或其他东西,但现在是 KISS :)
    • 很好的解决方案!但是,我将我的函数称为“with_article”。干杯!
    • 当涉及到像hour 这样不以元音开头的字符串时,它将失败。
    • 同样,对于一些以这 5 个字母之一开头但带“a”的单词也会失败,例如university
    猜你喜欢
    • 2011-07-19
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-01-19
    • 2022-11-20
    • 1970-01-01
    • 2020-11-30
    • 1970-01-01
    相关资源
    最近更新 更多