ruby - what's a clean way of finding which common elements exist in a set of n arrays? -
i'm going through table in database has lot of optional columns. i'm wanting find columns have data in every record in database.
a simplified example of i'm trying follows:
[1,2,3,4,5] & [1,2,3,4] & [1,2,3] & [1,2] #=> [1,2]
however, i'm trying run type of operation thousands of records. what's clean way accomplish this? have feeling ruby might have bespoke methods sort of thing.
here's before decided write question:
sets_of_columns_with_data = tablename.all.map(&:attributes).map |attrs| attrs.select {|k,v| v} end.map(&:keys)
so @ point, if following above code, columns_with_data
equivalent of this:
sets_of_columns_with_data = [ [1,2,3,4,5], [1,2,3,4], [1,2,3] [1,2] ]
a messy way guess this:
always_used = sets_of_columns_with_data.first sets_of_columns_with_data.each |columns_with_data| always_used = always_used & columns_with_data end
what's clean, ruby-way this?
thanks
note:
i'm keeping business logic sake of clarity, not best solution when have sql available you.
i'm not sure if solves actual problem, apply binary operation, can use reduce
:
sets_of_columns_with_data = [ [1, 2, 3, 4, 5], [1, 2, 3, 4], [1, 2, 3], [1, 2] ] sets_of_columns_with_data.reduce(:&) #=> [1, 2]
Comments
Post a Comment