I've been finding this quite useful - especially when partition just isn't enough:
def to_hash(&block) return {nil => self} unless block_given? the_hash = {} self.each do |val| key = block.call(val) the_hash[key] ||= [] the_hash[key] << val end the_hash end
Usage examples:
[1,2,3,4,5,6].to_hash {|v| v % 3 } => {0=>[3,6], 1=>[1, 4], 2=>[2, 5]} Widget.all.to_hash {|w| w.status } => {:pending => [<Widget1>,<Widget4>], :complete => [<Widget2>], :awaiting_approval =>[<Widget3>]}
2 comments:
Just so you know there's Array#group_by in standard library since ruby 1.8.7 that seems to be doing the same thing.
Ah! So there is!
When I went looking I couldn't find what I wanted - of course it's in Enumerable, rather than Array.
Ok, thanks for the tip, and good spotting!
Everyone else: nothing to see here then... :)
Post a Comment