user1908375
user1908375

Reputation: 1089

exclude elements from hash based on array

I have an array of hashes

x = [{:name=>'a', :value=1}, {:name=>'b', :value=2}, {:name=>'c', :value=3}]

and string array

y = ["a", "c"]

how could I exclude elements from x based on y ? so that at the end I have x = [ {:name=>'b', :value=2} ]

Upvotes: 1

Views: 89

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

Although the answer provided by @Santhosh is absolutely correct, on huge arrays it is not efficient due to lookup in y on each iteration. That might be faster:

xgr = x.group_by { |e| e[:name] }
x - y.map { |e| xgr[e] }.flatten
#⇒ [ {:name=>'b', :value=2} ]

Upvotes: 1

Santhosh
Santhosh

Reputation: 29144

Use Enumerable#reject

x.reject {|h| y.include? h[:name]}
# => [{:name=>"b", :value=>2}]

Note: If you want to modify the original object, you can use reject! instead.

Upvotes: 4

Related Questions