Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any method similar to in_groups_of in rails but for hash?

I want to split this hash in groups of size number, let's just say 2 items per group

hash = {'[email protected]': {name: 'name 1'},
        '[email protected]': {name: 'name 2'},
        '[email protected]': {name: 'name 3'},
        '[email protected]': {name: 'name 4'},
        '[email protected]': {name: 'name 5'}
       }

wanted result should be:

hash1 = {'[email protected]': {name: 'name 1'},
        '[email protected]': {name: 'name 2'}}

hash2 = {'[email protected]': {name: 'name 3'},
        '[email protected]': {name: 'name 4'}}

hash3 = {'[email protected]': {name: 'name 5'}}
like image 617
RSync Avatar asked Nov 30 '25 16:11

RSync


1 Answers

You can use Enumerable#each_slice, after that map each element as a hash with Array#to_h:

hash1, hash2, hash3 = hash.each_slice(2).map(&:to_h)
p hash1 # {:"[email protected]"=>{:name=>"name 1"}, :"[email protected]"=>{:name=>"name 2"}}
p hash2 # {:"[email protected]"=>{:name=>"name 3"}, :"[email protected]"=>{:name=>"name 4"}}
p hash3 # {:"[email protected]"=>{:name=>"name 5"}}
like image 97
Sebastian Palma Avatar answered Dec 02 '25 05:12

Sebastian Palma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!