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"}]
[{说:2,:“李”}]
3 个解决方案
#1
5
If you want to select only the elements where the value of :dis
is included in x
:
如果您只想选择x中包含:dis值的元素:
y.select{|h| x.include? h[:dis]}
#2
0
Yes use select
, nonetheless here's another way which works:
是的,使用select,尽管如此还有另一种方法:
y.each_with_object([]) { |hash,obj| obj << hash if x.include? hash[:dis] }
#3
0
You can delete the nonconforming elements of y
in place with with .keep_if
可以使用.keep_if删除不符合要求的y元素
> y.keep_if { |h| x.include? h[:dis] }
Or reverse the logic with .delete_if:
或将逻辑与.delete_if反向:
> y.delete_if { |h| !x.include? h[:dis] }
All produce:
所有的生产:
> y
=> [{:dis=>2, :as=>"li"}]
#1
5
If you want to select only the elements where the value of :dis
is included in x
:
如果您只想选择x中包含:dis值的元素:
y.select{|h| x.include? h[:dis]}
#2
0
Yes use select
, nonetheless here's another way which works:
是的,使用select,尽管如此还有另一种方法:
y.each_with_object([]) { |hash,obj| obj << hash if x.include? hash[:dis] }
#3
0
You can delete the nonconforming elements of y
in place with with .keep_if
可以使用.keep_if删除不符合要求的y元素
> y.keep_if { |h| x.include? h[:dis] }
Or reverse the logic with .delete_if:
或将逻辑与.delete_if反向:
> y.delete_if { |h| !x.include? h[:dis] }
All produce:
所有的生产:
> y
=> [{:dis=>2, :as=>"li"}]