Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper usage of REJECT method in Ruby on Rails -- help me convert many lines into Ruby one-liner

I have an array of hashed names and emails, like this:

array = [{"email"=>"[email protected]", "name"=>"Test"},
      {"email"=>"[email protected]", "name"=>"Test A"},
      {"name"=>"Test B", "email"=>"[email protected]"},
      {"email"=>"[email protected]", "name"=>"Test C"},
      {"name"=>"Test D", "email"=>"[email protected]"},
      {"email"=>"[email protected]"},
      {"name"=>"Test F", "email"=>"[email protected]"}]

I want to filter out certain emails in a "blacklist" array. The following works, but it's too verbose.

 blacklist = ["@test.com", "@gmail.com"] 
 na = array
 blacklist.each do |b|
   na = na.reject{ |e| e["email"].include?(b) }
 end

 # na => [{"email"=>"[email protected]", "name"=>"Test C"}, {"name"=>"Test D", "email"=>"[email protected]"}]

Can someone help me by putting this into a sexy Ruby one-liner?

like image 208
MorningHacker Avatar asked Nov 18 '11 20:11

MorningHacker


1 Answers

One more suggestion :)

array.reject { |h| blacklist.any? { |b| h["email"].include? b } }
like image 71
WarHog Avatar answered Sep 23 '22 09:09

WarHog