Learning Ruby: Loops & Blocks

ยท 2 minute read

A loop is a control structure that allows you to repeatedly execute a block of code.

loop do
	puts "I'm looping..."
end

Loops ๐Ÿ”—

The above code is called an infinite loop because it won’t stop executing unless we add a clause.

20.times do
  puts "I'm looping..."
end
I'm looping...
I'm looping...
I'm looping...
.......
.......
I'm looping... (20th)

We could also do

1.upto(20) do
  puts "I'm looping..."
end

Also

1.upto(10) { |n| puts n }

While Loop ๐Ÿ”—

while <= 50
  puts "Not greater than or equals to 50, yet..."
  num += 1
end

Until Keyword ๐Ÿ”—

until num > 50
	puts "Not there yet..."
  num += 1
end

.each ๐Ÿ”—

nums = [1, 2, 3, 4, 5]
nums.each { |num| puts num}

output:
1
2
3
4
5

Code Blocks ๐Ÿ”—

They are nameless methods. They can be passed into other methods or stored for later use.

negative_nums = [-1, -2, -3, -4, -5]
positive_nums = negative_nums { |num| mum.abs}

output:
[1, 2, 3, 4, 5]

Code blocks can also be passed into methods for reusability. Each method call below will produce a different result.

def play_with_each_toy(toy_box, &instructions)
  toy_box.each do |toy|
    instructions.call(toy)
  end
end

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

play_with_each_toy(toys) do |toy|
  puts toy * 2
end

play_with_each_toy(toys) do |toy|
  puts toy * 4
end

We could also use the yield keyword to achieve the same result

def play_with_each_toy(toy_box)
  toy_box.each do |toy|
    yield(toy * 2)
  end
end

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

play_with_each_toy(toys) do |result|
  puts result
end

Also, we could save a block for later use

saved_block = Proc.new { |x| x * 3 }

result = saved_block.call(5)
puts "Result from saved block: #{result}"

if block_given? ๐Ÿ”—

Calling a blocked method without a block will return an error. Even with using the yield keyword. We solve this using a conditional

def play_with_each_toy(toy_box, &instructions)
  toy_box.each do |toy|
    instructions.call(toy) if block_given?
  end
end

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

# Using the block
play_with_each_toy(toys) do |toy|
  puts toy * 3
end

# Without providing a block
play_with_each_toy(toys)

We can also create a code block with lambda and stubby_lambda

# Using lambda keyword
my_lambda = lambda { |x| puts x * 2 }
my_lambda.call(5)  # Output: 10
# Using stabby lambda syntax
my_stabby_lambda = ->(x) { puts x * 2 }
my_stabby_lambda.call(5)  # Output: 10

๐Ÿ‘‰๐Ÿฝ See all notes in this series