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. can receive a “default value” to return for keys he has no values for. so‘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}

Posted by:

Dor Kalev, CTO @ FTBpro

blog comments powered by Disqus