为什么这种多元化名称的方法在所有情况下都不起作用?

时间:2010-07-22 11:44:19

标签: ruby regex

PLURALIZATION_EXCEPTIONS = "hardware",'memory'
def pluralize_category_name(name)
  category = name.split(' and ')
  exceptions_to_exp = ""

  category.map! { |e| 
    if e.match(/^[A-Z]+$/)  and !e.match(/^[A-Z]+S$/)
      e = e.pluralize
    end
    (PLURALIZATION_EXCEPTIONS.include?(e.downcase)  || e.match(/^[A-Z]+S$/) ||
      e.match(/[memory|hardware]/) )? e : e.pluralize
  }.join(' and ')
end

测试应该和期望如下:

it "properly pluralizes hardware as hardware" do
   pluralize_category_name("hardware").should == "hardware"
end

it "properly pluralizes UPS as UPS" do
   pluralize_category_name("UPS").should == "UPS"
end

it "properly pluralizes PDA and Portable Hardware as PDAs and Portable Hardware" do
   pluralize_category_name("PDA and Portable Hardware").should == "PDAs and Portable Hardware"
end

it "properly pluralizes perfume and cologne as perfumes and colognes" do
   pluralize_category_name("perfume and cologne").should == "perfumes and colognes"
end

最后一次测试失败:(

HELP!

1 个答案:

答案 0 :(得分:2)

我认为你的问题是你的情况

(PLURALIZATION_EXCEPTIONS.include?(e.downcase)  || e.match(/^[A-Z]+S$/) ||
      e.match(/[memory|hardware]/) )? e : e.pluralize

"perfume"匹配/[memory|hardware]/

[memory|hardware]character class,可与memor等任意内容相匹配..

也许您的意思是e.match(/(memory|hardware)]/i)?这种替代模式会通过您的测试,但它不会使用您的PLURALIZATION_EXCEPTIONS常量,因此如果您添加了任何其他异常,则需要更新。