Search code examples
ruby-on-railshashruby-on-rails-5

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

Solution

  • 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"}}