newUserNameHere
newUserNameHere

Reputation: 17981

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}]

Upvotes: 1

Views: 260

Answers (2)

steenslag
steenslag

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

lurker
lurker

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

Related Questions