也許是這樣的。
key_to_category = { "red"=>1, "blue"=>2, "green"=>3, "pink"=>2 }
keys = key_to_category.keys
#=> ["red", "blue", "green", "pink"]
cats = key_to_category.values.uniq
#=> [1, 2, 3]
products = [
"Red and Green Gummies",
"Sky-Blue Thingamajigs",
"Dead Fred",
"Green Glue",
"Blue and Green Whatchamacallits"
]
r =/
\b # match word break
#{Regexp.union(keys)} # match any key
\b # match word break
/x # extended/free-spacing regex definition mode
#=>/
\b
(?-mix:red|blue|green|pink)
\b
/x
products.each_with_object(Hash.new { |h,k| h[k] = [] }) do |prod, h|
prod.downcase.scan(r).each { |key| h[key_to_category[key]] << prod }
end
#=> {1=>["Red and Green Gummies"],
# 3=>["Red and Green Gummies", "Green Glue",
# "Blue and Green Whatchamacallits"],
# 2=>["Sky-Blue Thingamajigs", "Blue and Green Whatchamacallits"]}
然後逐步完成更新。
可替代地,步驟通過產品表,獲得product_name
,計算
product_name = "Red and Green Gummies"
key_to_category.values_at(*product_name.downcase.scan(r))
#=> [1, 3]
,然後更新類別1和3
這是有點模糊的問題,但如果是我我會首先學習這[算法](https://en.wikipedia.org/wiki/String_searching_algorithm) – bjhaid