Ruby Basics: Iterating Through Collections

Ethan Collins
Ethan Web Dev
Published in
2 min readAug 5, 2019

I started learning Ruby around three weeks ago, and the change in the efficiency of my programming is significant. Long and ugly pieces of code have become more concise, as well as being easier to read.

Non-specific enumerators such as “.each” have been replaced by more specific enumerators like “.map” or “.select”. Starting at flatiron, if asked to iterate through an array to find a value, I would have large clunky code. For example:, if asked to find the largest string in an array of names:

array = ["Bob", "Rob", "Bobby", "Roberto"]
largest = ""
array.each do |name|
if name.length > largest.length
largest = name
end
end
return largest=> "Roberto"

This works, but it isn’t very efficient nor as instantly readable as using an enumerator such as “max_by”

array = ["Bob", "Rob", "Bobby", "Roberto"]array.max_by(&:length)=> "Roberto"

Now that reads much more cleanly. Looking at the one line, I can see that I want to iterate through an array, returning the element with the greatest (“max_by”) length.

Another example is “.reduce”, returning one value from a set of values. If I wanted to return the sum of every value in an array, I could do so again using each:

array = [0, 7, 2, 3]
sum = 0
array.each do |number|
sum += number
end
return sum

Again, this is functional, but we can do better.

array = [0, 7, 2, 3]
array.reduce(0) {|sum, num| sum + num}

Time for a coffee break, and don’t forget that syntactic sugar.

--

--