Reputation: 17981
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}]
Upvotes: 1
Views: 260
Reputation: 80065
h = {:a=>1, :b=>2, :c=>3, :d=>4}
p h.each_slice(2).map{|slice| Hash[slice]} # => [{:a=>1, :b=>2}, {:c=>3, :d=>4}]
Upvotes: 4
Reputation: 58244
One way to do it:
arr = []
a.each_slice(2) {|s| arr << Hash[s]}
Choose whatever value you want for the 2
above.
As a method:
def slice( a, n )
arr = []
a.each_slice(n) {|s| arr << Hash[s]}
arr
end
Or simpler:
def slice( a, n )
a.each_slice(n).inject([]) {|a, p| a << Hash[p]}
end
Upvotes: 2