Saturday, 14 September 2013

Slicing a Hash into equal slices using Ruby

Slicing a Hash into equal slices using Ruby

How would you slice a hash into an array of equal hash slices using ruby?
Particularly something like this:
ORIGINAL HASH
a = {:a=>1, :b=>2, :c=>3, :d=>4}
EDIT: Adding answer here from below for quick reference. See below for a
better explanation.
SOME CODE HERE TO SLICE INTO SAY 2 EQUAL SLICES
a.each_slice(2).map{|slice| Hash[slice]}
RESULT
a = [{:a=>1, :b=>2}, {:c=>3, :d=>4}]

No comments:

Post a Comment