Skip to content

Instantly share code, notes, and snippets.

@nickserv
Last active September 6, 2024 19:05
Show Gist options
  • Save nickserv/9106736 to your computer and use it in GitHub Desktop.
Save nickserv/9106736 to your computer and use it in GitHub Desktop.
Ruby Enumerable Guide

A before-and-after guide to Ruby's Enumerable module

Basics

each

Ruby's for keyword is an anti pattern! In fact, it's actually slower than each and uses each in the background.

Before

for n in [1, 2, 3, 4]
  puts n
end

After

[1, 2, 3, 4].each do |n|
  puts n
end

map (also known as collect)

Map is useful when you need to change every value in an Enumerable.

Before

doubles = []
[1, 2, 3, 4].each do |n|
  doubles << n * 2
end

After

[1, 2, 3, 4].map do |n|
  n * 2
end

reduce (also known as inject, or fold in other languages)

Reduce is useful when you want to gradually create a value based on each element in an Enumerable.

Before

sum = 0
[1, 2, 3, 4].each do |n|
  sum += n
end
sum

After

[1, 2, 3, 4].reduce(0) do |sum, n|
  sum + n
end

each_with_object

This is similar to reduce, except you don't have to explicitly return a new value for the accumulator.

Before

words = ['one', 'two', 'two', 'three', 'three', 'three']
words.reduce(Hash.new(0)) do |occurrences, str|
  occurrences[str] += 1
  occurrences
end

After

words = ['one', 'two', 'two', 'three', 'three', 'three']
words.each_with_object(Hash.new(0)) do |str, occurrences|
  occurrences[str] += 1
end

Methods for checking conditions

all?

all? is handy for checking if each element in an Enumerable meet a given condition.

Before

all_odd = true
[1, 2, 3].each |n|
  if n.even?
    all_odd = false
    break
  end
end

After

[1, 2, 3].all? |n|
  n.odd?
end

any?

any? is handy for checking if there is any element in an Enumerable that meets a given condition.

Before

any_even = false
[1, 2, 3].each |n|
  any_even = true if n.even?
end

After

[1, 2, 3].any? |n|
  n.even?
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment