简体   繁体   中英

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"=>"test@test.com", "name"=>"Test"},
      {"email"=>"testA@gmail.com", "name"=>"Test A"},
      {"name"=>"Test B", "email"=>"testB@test.com"},
      {"email"=>"testC@yahoo.com", "name"=>"Test C"},
      {"name"=>"Test D", "email"=>"testD@hotmail.com"},
      {"email"=>"testE@test.com"},
      {"name"=>"Test F", "email"=>"testF@test.com"}]

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"=>"testC@yahoo.com", "name"=>"Test C"}, {"name"=>"Test D", "email"=>"testD@hotmail.com"}]

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

还有一个建议:)

array.reject { |h| blacklist.any? { |b| h["email"].include? b } }
people.reject { |p| blacklist.include?("@" + p["email"].split("@", 2)[1]) }

Note that you should build the blacklist as a set to make the inclussion test O(1).

require 'set'
blacklist = ["@test.com", "@gmail.com"].to_set

If this hash is coming from the DB, then you should do the filtering on the DB side.

If not, then don't run a separate reject for each blacklist item. You probably want something like

array.reject {|rec| blacklist.include? "@#{rec['email'].split('@').last}" }
array = [{"email"=>"test@test.com", "name"=>"Test"},
      {"email"=>"testA@gmail.com", "name"=>"Test A"},
      {"name"=>"Test B", "email"=>"testB@test.com"},
      {"email"=>"testC@yahoo.com", "name"=>"Test C"},
      {"name"=>"Test D", "email"=>"testD@hotmail.com"},
      {"email"=>"testE@test.com"},
      {"name"=>"Test F", "email"=>"testF@test.com"}]

blacklist = ["test.com", "gmail.com"] 
na = array.reject { |e| blacklist.include?(e["email"].split('@').last) }

=> [{"name"=>"Test C", "email"=>"testC@yahoo.com"}, {"name"=>"Test D", "email"=>"testD@hotmail.com"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM