我在下面列出的ruby代码中有一个if else条件:
if !category.nil?
return false unless company_matches.any? { |w|
comparison = /(\s|^)#{w}(\s|$)/i
(title.index(comparison) || description.index(comparison) || clean_title.index(comparison) || clean_desc.index(comparison)) && (category == 'Business')}
else
return false unless company_matches.any? { |w|
comparison = /(\s|^)#{w}(\s|$)/i
(title.index(comparison) || description.index(comparison) || clean_title.index(comparison) || clean_desc.index(comparison))}
end
我如何简化它以使其看起来更微妙?
答案 0 :(得分:1)
company_matches.any? do |company|
[title, description, clean_title, clean_desc].any? do |attribute|
attribute.match? /(\s|^)#{company}(\s|$)/i
end && (category == 'Business' || category.nil?)
end
答案 1 :(得分:0)
您可以创建一种方法来进行比较,这样您就不会重复自己。您还可以从comparison
块中抽象出if .. else
变量。这就是我所拥有的:
comparison = /(\s|^)#{w}(\s|$)/i
result = perform_comparison(title, description, clean_title, clean_desc, comparison)
unless category.nil?
return false unless company_matches.any? { |w| result && (category == 'Business')}
else
return false unless company_matches.any? { |w| result }
end
# somewhere else in your code
def perform_comparison(title, description, clean_title, clean_desc, comparison)
title.index(comparison) || description.index(comparison) || clean_title.index(comparison) || clean_desc.index(comparison)
end