linuxNoob
linuxNoob

Reputation: 720

Ruby - Filtering array of hashes based on another array

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

Upvotes: 5

Views: 4740

Answers (3)

dawg
dawg

Reputation: 103764

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

Upvotes: 1

Mark Thomas
Mark Thomas

Reputation: 37517

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

y.select{|h| x.include? h[:dis]}

Upvotes: 7

Sagar Pandya
Sagar Pandya

Reputation: 9497

Yes use select, nonetheless here's another way which works:

y.each_with_object([]) { |hash,obj| obj << hash if x.include? hash[:dis] }

Upvotes: 0

Related Questions