Filter array of arrays with an array in Ruby -


looking more efficient way of filtering array of arrays using array in ruby. let me demonstrate. starting this:

core = [[1, "apple", "james bond"],         [5, "orange", "thor"],         [10, "banana", "wolverine"],         [15, "orange", "batman"],         [20, "apple", "mickey mouse"],         [25, "orange", "lee adama"],         [30, "banana", "luke skywalker"]]  filter = ["apple", "banana"]  result = core.magical_function(filter)  # result == [[5, "orange", "thor"], #            [15, "orange", "batman"], #            [25, "orange", "lee adama"]] 

the thing can think of looping through filter elements, slows down code lot when toy example gets more complicated.

use array#reject , array#include?:

core.reject { |_,fruit,_| filter.include?(fruit) }   # => [[5, "orange", "thor"], [15, "orange", "batman"], [25, "orange", "lee adama"]] 

if filter large, first convert set faster lookups:

require 'set' filter_set = filter.to_set core.reject { |_,fruit,_| filter_set.include?(fruit) } 

see set , instance methods. when required, set adds instance method to_set module enumerable inclueded array. ruby implements sets unseen hashes.


Comments

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -