Collections

Enumerable is a mixin  that allows you to traverse  a collection. Although they are all pretty exciting `each_with_object` is one of the more exciting ruby enumerables. Basically it does exactly what is says on the tin, it works just like each, but passes the current element and the object to the block every time it iterates.

Let’s demonstrate a very simple example, say we want to count the number of occurrences of every word in a collection;

my_array = %w(rails girls rock rails girls rock rails girls rock always)
=> [“rails”, “girls”, “rock”, “rails”, “girls”, “rock”, “rails”, “girls”, “rock”, “always”]

my_array.each_with_object(Hash.new(0)) { |word, count| count[word] += 1}
=> {“rails”=>3, “girls”=>3, “rock”=>3, “always”=>1}

ta-da and you’re done! Psst word is the word you’d get in a normal each, and count is the object referred to by using with_object (so, the hash). Just a reminder Hash.new(0) sets default value for any key to 0, while {} sets it to nil

Hope to see you at Rails Girls BNE (21/22 July /17) 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *