The aesthetics of Ruby - Kernel#itself method
Recently, I’ve had quite a popular problem to solve: count the occurences of the given item in a collection. There are few ways to solve this problem - starting from using Enumerable#inject or Enumerable#each_with_object with an empty hash as an accumulator value and writing a code looking like this:
rb
collection.each_with_object({}) { |item, accum| accum[item] = accum[item].to_i + 1 }
through a bit smarter way and taking advantage of the default hash value:
rb
collection.each_with_object(Hash.new(0)) { |item, accum| accum[item] = accum[item] + 1 }
All these solutions look quite nice; however, there is one that looks particularly beautiful.
Post a comment