image by David Streit
Enumerable avoids using temporary variables when looping
Some of my favourite Ruby features are to be found in the
Enumerable module. You can read more about it in the Ruby documentation.
A class representing a collection, such as
Hash, has the methods and features of
Enumerable included. These methods allow you to loop through the members of that group and take an action using each member of the collection as an input.
…using a C-style loop with a temporary variable, which would be fine in many other languages.
total = 0 [1, 3, 5, 7].each do |num| total += num end total
…your deep love of one of Ruby’s
Enumerable methods, and implement using
[1, 3, 5, 7].inject(0) do |total, number| total += number end
…there’s a convenient
#sum method in
[1, 3, 5, 7].sum
The longer I’ve used Ruby the more joy I find in the elegance enabled by its
Enumerable methods. Using these constructions lead you write idiomatic Ruby, which is a smart sounding way of saying you’re writing Ruby in a Ruby-ish manner.
When dealing with larger loops there are often significant improvements to memory usage and speed when using built-in
If you ever see the “temporary variable setup” at the beginning of a loop there’s most likely an opportunity to express yourself more concisely with an
#inject might seem confusing and be unfamiliar to newer Rubyists. They are a fundamental benefit of using Ruby, so you might as well dive in.
Last updated on February 5th, 2018 by @andycroll
An email newsletter, with one Ruby/Rails technique delivered with a ‘why?’ and a ‘how?’ every two weeks. It’s deliberately brief, focussed & opinionated.