Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Filtering array of hashes based on another array

Tags:

arrays

ruby

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"}]

like image 579
linuxNoob Avatar asked Jul 07 '17 15:07

linuxNoob


2 Answers

If you want to select only the elements where the value of :dis is included in x:

y.select{|h| x.include? h[:dis]}
like image 178
Mark Thomas Avatar answered Nov 17 '22 04:11

Mark Thomas


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"}]
like image 1
dawg Avatar answered Nov 17 '22 02:11

dawg