Monday, October 18, 2010

Hash#in_groups_of

Here is a quick and dirty snippet to distribute a Hash into an Array of mini-Hashes as an analogue to the Rails Array#in_groups_of method.


module MyHashExtensions
def in_groups_of(*args)
to_a.in_groups_of(*args).inject([]) do |accum, group|
accum << group.inject({}) {|acc, pair| pair.nil? ? acc : acc.merge(pair.first => pair.last)}
end
end
end
end

Hash.class_eval do # jam this into Hash however you wish!
include MyHashExtensions
end


Example usage:

{:a => 'b', :c => 'd', :e => 'f', :g => 'h', :i => 'j', :k => 'l', :m => 'n'}.in_groups_of(3)


gives...


[{:i=>"j", :e=>"f", :g=>"h"}, {:c=>"d", :a=>"b", :k=>"l"}, {:m=>"n"}]


I used this for Cassandra/Rails/Thrift experimentation today! Remember, the text buffer is your canvas. You are a software artist, whether you like it or not. Play with the code, and if someone doesn't like it, throat punch them.