如何将数组哈希与单个哈希进行比较,并返回包含比较结果的新哈希数组。
例如:
stored_hash = [
{:a => 1, :b => 2, :c => 3},
{:a => 1, :b => 3, :c => 4}
]
compare_hash = {:a => 1}
stored_hash.some_function_here(compare_hash)
应该返回:
[
{:a => 1, :b => 2, :c => 3},
{:a => 1, :b => 3, :c => 4}
]
虽然这个:
stored_hash = [
{:a => 1, :b => 2, :c => 3},
{:a => 1, :b => 3, :c => 4}
]
compare_hash = {:a => 1, :b => 3}
stored_hash.some_function_here(compare_hash)
应该返回:
[
{:a => 1, :b => 3, :c => 4}
]
答案 0 :(得分:5)
这是一种方法,使用Array#keep_if
和Hash#merge
stored_hash.keep_if {|hash| hash.merge(compare_hash) == hash}
答案 1 :(得分:1)
你可以这样做:
def matches(stored_hash, compare_hash)
stored_hash.select do |h|
h.values_at(*compare_hash.keys) == compare_hash.values
end
end
stored_hash = [
{:a => 1, :b => 2, :c => 3},
{:a => 1, :b => 3, :c => 4}
]
compare_hash = {:a => 1}
matches(stored_hash, compare_hash)
#=> [{:a=>1, :b=>2, :c=>3}, {:a=>1, :b=>3, :c=>4}]
compare_hash = {:a => 1, :b => 3}
matches(stored_hash, compare_hash)
#=> [{:a=>1, :b=>3, :c=>4}]
答案 2 :(得分:0)
除非你想修补Array
,否则你不会在stored_hash
上调用方法,但你可以这样做:
def some_function(haystack, needle)
haystack.select do |hash|
needle.all? { |k,v| hash[k] == v }
end
end
然后用
调用它some_function(stored_hash, compare_hash)
另外,请注意您的stored_hash
不是哈希,它是一个数组;这个名字有点误导。
答案 3 :(得分:0)
另一种方式:
def find_matches(stored_hash, compare_hash)
stored_hash.find_all {|h| h.to_a & compare_hash.to_a == compare_hash.to_a}
end
compare_hash = {:a=>1, :b=>2}
find_matches(stored_hash, compare_hash)
#=> [{:a=>1, :b=>2, :c=>3}]
compare_hash = {:a=>1}
find_matches(stored_hash, compare_hash)
#=> [{:a=>1, :b=>2, :c=>3}, {:a=>1, :b=>3, :c=>4}]