Reputation: 1089
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
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
Reputation: 29144
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