Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@citizen428
Created November 22, 2011 20:46
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 citizen428/1386892 to your computer and use it in GitHub Desktop.
Save citizen428/1386892 to your computer and use it in GitHub Desktop.
A snippet I used for explaining the map/reduce paradigm
>> words = "foo bar baz qux foo bar lala"
#=> "foo bar baz qux foo bar lala"
>> # map (user-supplied)
.. mapped = words.split(/ /).map { |w| [w,1] }
#=> [["foo", 1], ["bar", 1], ["baz", 1], ["qux", 1], ["foo", 1], ["bar", 1], ["lala", 1]]
>> # aggregate (built-in)
.. aggregated = mapped.group_by { |w, c| w }
#=> {"foo"=>[["foo", 1], ["foo", 1]], "bar"=>[["bar", 1], ["bar", 1]], "baz"=>[["baz", 1]], "qux"=>[["qux", 1]], "lala"=>[["lala", 1]]}
>> # reduce (user-supplied)
>> aggregated.each_with_object({}) { |(k, v), h| h[k] = v.map(&:last).inject(:+) }
#=> {"foo"=>2, "bar"=>2, "baz"=>1, "qux"=>1, "lala"=>1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment