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.
-Dave
--
Dave Aronson, consulting software developer of Codosaur.us,
PullRequestRoulette.com, Blog.Codosaur.us, and Dare2XL.com.
--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/CAHxKQigrkwt6RQ1zJbR1zu6WWPkq%3DYRGN_4B5ARmbQoFMCrQMQ%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.
No comments:
Post a Comment