Tips for understanding the each loop in ruby

August 4, 2016   

I've had some students ask me about the .each loop in ruby :D Hopefully I can clarify some things.

Different Ways to Write .each Loop

numbers = [1, 2, 3, 4, 5]

# one way to loop numbers.each { |item| puts item }

# another way to loop numbers.each do |item| puts item end

Above, we see two ways to write the each loop. Which one is better?

The answer is, it depends. If the code is really short, then it makes sense to write it as a one liner. But if it's longer, it's better to write it as a do end block.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

numbers.each { |number| puts number } # this is better as one liner

numbers.each do |number| puts number puts “Hello World” puts “Another thing” puts “Do another thing” end # this is better with each do, since doing this in # one line would be very messy :)

In ruby, there are often multiple ways of writing code. Ruby developers tend to like shorter and more concise code :) For example, the if statement can even be written as a one-liner:

if some_condition
  puts “TECHRISE students are awesome”
end

# the above is OK, but we can rewrite it like this

puts “TECHRISE students are awesome” if some_condition

# this is considered to be cleaner and many ruby programmers # prefer this style

Pretty cool right? :)

What is this || thing?

When you are using each loops, you'll encounter these || things. You're probably wondering what these are :)

Let's take a look at the following:

numbers = [1, 2, 3, 4, 5]
numbers.each do |number|
  puts number
end

# this will print out # 1 # 2 # 3 # 4 # 5

Notice how we have |number|. These placeholders only work within the loop and not outside:

numbers = [1, 2, 3, 4, 5]
numbers.each do |number|
  puts number
end

puts number

# returns an error => “NameError: undefined local variable or method `number' for main:Object”

You can name these placeholders whatever you want:

numbers = [1, 2, 3, 4, 5]
numbers.each do |momo|
  puts momo
end

# still prints out all of the numbers

numbers = [1, 2, 3, 4, 5] numbers.each do |dog| puts dog end

# still prints out all of the numbers

However, we should name the placeholder something that makes sense.

  • Be careful of pluralization
    • If it's singular, name it a singular placeholder (number)
    • If it's pluralization, name it a plural placeholder (numbers)
  • The name should represent what the item is

Originally posted in TECHRISE Community at www.techrise.me