Skip to content

Instantly share code, notes, and snippets.

@nuboat
Created April 26, 2014 15:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nuboat/11322665 to your computer and use it in GitHub Desktop.
Save nuboat/11322665 to your computer and use it in GitHub Desktop.
MapReduce.rb
{1=>[1,1],
3=>[1,1,1,1],
5=>[1,1,1]
7=>[1,1],
2=>[1,1,1]}
require 'pp'
nums = [1,3,5,7,2,3,1,3,2,5,2,3,5,7]
maps = nums.map { |e| {:key=>e, :value=>1} }
hashes = maps.group_by { |hash| hash[:key] }
pp hashes
{1=>[{:key=>1, :value=>1}, {:key=>1, :value=>1}],
3=>
[{:key=>3, :value=>1},
{:key=>3, :value=>1},
{:key=>3, :value=>1},
{:key=>3, :value=>1}],
5=>[{:key=>5, :value=>1}, {:key=>5, :value=>1}, {:key=>5, :value=>1}],
7=>[{:key=>7, :value=>1}, {:key=>7, :value=>1}],
2=>[{:key=>2, :value=>1}, {:key=>2, :value=>1}, {:key=>2, :value=>1}]}
@schalermthai
Copy link

ผมเล่นด้วย

nums = [1,3,5,7,2,3,1,3,2,5,2,3,5,7]
hash = nums.each_with_object(Hash.new {[]}) { |v, hash| hash[v] <<= 1 }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment