RubyFlow The Ruby and Rails community linklog

×

The Ruby and Rails community linklog

Made a library? Written a blog post? Found a useful tutorial? Share it with the Ruby community here or just enjoy what everyone else has found!

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.

Read more

Post a comment

You can use basic HTML markup (e.g. <a>) or Markdown.

As you are not logged in, you will be
directed via GitHub to signup or sign in