I am trying to filter an array of hashes based on another array. What's the best way to accomplish this? Here are the 2 brutes I've right now:
x=[1,2,3]
y = [{dis:4,as:"hi"},{dis:2,as:"li"}]
1) aa = []
x.each do |a|
qq = y.select{|k,v| k[:dis]==a}
aa+=qq unless qq.empty?
end
2) q = []
y.each do |k,v|
x.each do |ele|
if k[:dis]==ele
q << {dis: ele,as: k[:as]}
end
end
end
Here's the output I'm intending:
[{dis:2,as:"li"}]
If you want to select only the elements where the value of :dis
is included in x
:
y.select{|h| x.include? h[:dis]}
You can delete the nonconforming elements of y
in place with with .keep_if
> y.keep_if { |h| x.include? h[:dis] }
Or reverse the logic with .delete_if:
> y.delete_if { |h| !x.include? h[:dis] }
All produce:
> y
=> [{:dis=>2, :as=>"li"}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With