我想将此哈希分成大小数组,每组仅2个项目
hash = {'mail1@email.com': {name: 'name 1'},
'mail2@email.com': {name: 'name 2'},
'mail3@email.com': {name: 'name 3'},
'mail4@email.com': {name: 'name 4'},
'mail5@email.com': {name: 'name 5'}
}
想要的结果应该是:
hash1 = {'mail1@email.com': {name: 'name 1'},
'mail2@email.com': {name: 'name 2'}}
hash2 = {'mail3@email.com': {name: 'name 3'},
'mail4@email.com': {name: 'name 4'}}
hash3 = {'mail5@email.com': {name: 'name 5'}}
答案 0 :(得分:1)
您可以使用Enumerable#each_slice
,之后将每个元素映射为Array#to_h
的哈希:
hash1, hash2, hash3 = hash.each_slice(2).map(&:to_h)
p hash1 # {:"mail1@email.com"=>{:name=>"name 1"}, :"mail2@email.com"=>{:name=>"name 2"}}
p hash2 # {:"mail3@email.com"=>{:name=>"name 3"}, :"mail4@email.com"=>{:name=>"name 4"}}
p hash3 # {:"mail5@email.com"=>{:name=>"name 5"}}