Iteration Cheatsheet

By March 17, 2019 April 29th, 2019 Uncategorized

In this post, I will go over a few different methods for iterating over hashes and arrays. So let’s jump right into it!

For all of the following methods, we will use two pieces of example data.

array = [“one”, “two”, “three”]

hash = {:one => “one”, :two => “two”, :three => “three”}

The most basic way to iterate over an array or a hash is to use the #each method.

With an array: array.each {|element| element.upcase}

With a hash: hash.each {|key, value| value.upcase}

In both of our examples, we are not changing the strings to UPPERCASE, but the original data stored in our variable is unchanged. To use the uppercase strings we could either assign the results of our #each method to a new variable or use a different method: #map, a.k.a. #collect.

With an array: {|element| element.upcase}

Will yield: [“ONE”, “TWO”, “THREE”]

With a hash: {|key, value| value.upcase}

Will yield: {:one => “ONE”, :two => “TWO”, :three => “THREE”}

Collect and map are interchangeable. Both of these functions will change the original array. This means there is no need to assign our modified array to a new variable. There is one other incredibly useful method we can use to iterate over enumerable data types, #each_with_index. The each with index method provides an auto-incrementing integer to use within the block that we provide to the method.

With an array: array.each_with_index {|element, index| element = “#{i}. element”}

Will yield: [“1. one”, “2. two”, “3.three”]

With a hash: hash.each_with_index {|key, index| hash[key] = index}

Will yield: {:one => 1, :two => 2, :three => 3}

Note that these methods are non-destructive, meaning they will not change the original data. If you choose to use the each with index method be sure to save the results of the method call in a new variable.

Thanks for reading! I hope this helps some new coders.

Leave a Reply