Gotta ♥ Ruby’s syntax

Rarely do I see the usage of each_with_object and Hash instantiation with default value in Ruby code while they help writing shorter yet understandable code.

each_with_object can usually reduce 2 lines of code on iterations made for aggregations. each_with_object is similar to reduce/inject but a little friendlier when the starting element is a mutable object.

Hash.new can receive a “default value” to return for keys he has no values for. so Hash.new(‘koko’)[rand] will always return ‘koko’. Awesome enough it can even receive a block.

Let’s demonstrate it with the idea of writing a “letters counter”. A method that gets the string “there is a wild rose” and returns {“o”=>1, “d”=>1, “l”=>1, “w”=>1, “a”=>1, “s”=>2, “i”=>2, “r”=>2, “e”=>3, “h”=>1, “t”=>1}

https://gist.github.com/dorkalev/6608204

Posted by:

Dor Kalev, CTO @ FTBpro

blog comments powered by Disqus