Proper use of the REJECT method in Ruby on Rails - help me convert many lines to a single-line Ruby layer

I have an array of hashed names and letters, for example:

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 specific letters in a blacklist array. The following works, but it is too much.

  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 in a sexy ruby ​​single line?

+4
source share
4 answers

Another suggestion :)

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

Note that you must build a blacklist as a set to do an O (1) rejection check.

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

If this hash comes from the database, then you should do filtering on the database side.

If not, do not perform a separate reject for each item in the blacklist. You probably want something like

 array.reject {|rec| blacklist.include? "@#{rec['email'].split('@').last}" } 
+1
source
 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 "}] 
0
source

Source: https://habr.com/ru/post/1381962/


All Articles