這就是我該怎麼做的。
代碼
def fruit_match(some_array, another_hash, fruit)
other_vals = another_hash.values_at(*fruit)
return nil if other_vals.include?(nil)
some_array.find { |h| h.values_at(*fruit) == other_vals }
end
例子
some_array = [ { apple: 1, orange: 2, pineapple: 3, plum: 4 },
{ apple: 1, cherry: 7, pineapple: 6, plum: 2 },
{ apple: 6, cherry: 2, pineapple: 8, fig: 3 } ]
another_hash = { apple: 6, cherry: 4, pineapple: 8, quamquat: 5 }
fruit = [:apple, :pineapple]
fruit_match(some_array, another_hash, fruit)
#=> { :apple=>6, :cherry=>2, :pineapple=>8, :fig=>3 }
fruit = [:apple, :plum]
fruit_match(some_array, another_hash, fruit)
#=> nil
[編輯:,直到我看到@ 7stud的回答我沒有注意到的 「3-5」 的比賽。要求匹配的數量落入給定範圍內是一個有趣的變化。以下是我將如何解決這一要求。
代碼
def fruit_match(some_array, another_hash, fruit, limits)
other_vals = another_hash.values_at(*fruit)
some_array.select { |h| limits.cover?(h.values_at(*fruit)
.zip(other_vals)
.count {|e,o| e==o && e}) }
end
例
some_array = [ { apple: 1, orange: 2, pineapple: 1, cherry: 1 },
{ apple: 2, cherry: 7, pineapple: 6, plum: 2 },
{ apple: 6, cherry: 1, pineapple: 8, fig: 3 },
{ apple: 1, banana: 2, pineapple: 1, fig: 3 } ]
another_hash = { apple: 1, cherry: 1, pineapple: 1, quamquat: 1 }
fruit = [:apple, :pineapple, :cherry]
limits = (1..2)
fruit_match(some_array, another_hash, fruit, limits)
#=> [{:apple=>6, :cherry=>1, :pineapple=>8, :fig=>3},
# {:apple=>1, :banana=>2, :pineapple=>1, :fig=>3}]
潮]
Freakin真棒。比以前好多了。謝謝! – user2152283 2014-08-30 00:06:07
對於我的例子,用'fruit = [:apple,:plum]'返回'{:apple => 6,:cherry => 2,:pineapple => 8,:fig => 3}',但'another_hash '沒有鍵':plum',所以它應該返回'nil'。 – 2014-08-30 04:59:35
@CarySwoveland - 這兩個哈希函數都沒有':plum',所以它的工作方式與我的想法相符? :) – BroiSatse 2014-08-30 11:47:39