5

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
  • What's your desired output? Commented Jul 7, 2017 at 15:25
  • @MarkThomas updated Commented Jul 7, 2017 at 15:28

3 Answers 3

7

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

y.select{|h| x.include? h[:dis]}
Sign up to request clarification or add additional context in comments.

5 Comments

Simple and concise, thanks! I didn't know about include?
Just one more question - Is it a bad idea to use select!, would storing it off and re-using be preferable? I don't need y anywhere else.
The only possible improvement I can think of is to substitute the word "included" for "contained", so it reads "...select...included...".
Haha @CarySwoveland I thought the same thing, just didn't get around to updating it. Nice to meet a fellow pedant! (Now if we can just get the Ruby maintainers to make those methods plural...)
@linuxNoob Using select! is fine if you want to change it in place (or use keep_if which usually reads better to me).
1

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.