我想写一个简化公司名称的方法。我希望它按如下方式工作:
@clear_company = clear_company(@company.name)
会发生什么是@company.name = "Company, Inc."@clear_company 将是“公司”
如果@company.name = "Company Corporation"@clear_company 将是"Company"
不会有多余的空格。我查看了不同的 strip 和 gsub,但我需要维护一个数组:
clean_array = %w[Inc. Incorporated LLC]
我可以更新它以使其更有效。
我该怎么做?
最佳答案
在 lib/clear_company.rb 中:
module ClearCompany
BUSINESS_ENTITY = %w[Corporation Inc. Incorporated LLC]
def clear_company
strip_business_entity.remove_trailing_punctuation
end
def strip_business_entity
BUSINESS_ENTITY.inject(self) do |company, clean_word|
company.sub(clean_word, '')
end
end
def remove_trailing_punctuation
strip.sub(/,$/, '')
end
end
在 config/initializers/string.rb 中:
class String
include ClearCompany
end
如果你喜欢 RSpec:
describe String, :clear_company do
it "removes ', Inc.' from the end" do
"Company, Inc.".clear_company.should == "Company"
end
it "removes ' Corporation' from the end" do
"Company Corporation".clear_company.should == "Company"
end
end
关于ruby-on-rails - 如何为去除文本数组的多个 Controller 编写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3097629/