On Tue, Dec 23, 2014 at 10:54 PM, Roman Yarygin wrote:
> Solved it like that:
>
> abilities_array = []
> roles.map(&:abilities).flatten(1).each do |e|
> if i = abilities_array.find_index{|ar| ar[1]==e[1] && ar[2]==e[2]}
> abilities_array[i] = e
> else
> abilities_array << e
> end
> end
> abilities_array.map{|a| "#{a[0]} #{a[1]}, #{a[2]}#{", "+a[3] unless
> a[3].blank?}"}
I'm not even going to try to grok how that works. Using a temporary
hash as a filter is much simpler:
tmp_hash = {}
roles.map(&:abilities).each do |ability|
tmp_hash[ability[1,2]] = ability
end
abilities_array = tmp_hash.values
Or with tap:
abilities_array = {}.tap { |tmp_hash|
roles.map(&:abilities).each do |ability|
tmp_hash[ability[1,2]] = ability
end
}.values
(If you want *earlier* ones to take precedence, use ||= instead of =.)
Hashes are one of your bestest friends in the whole wide world. At
least, the world of Ruby. ;-) They're very fast, and extremely
useful.