Menu
Coddy logo textTech

Block Parameters

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 18 of 56.

The variables between the pipes, |x|, |x, y|, are the block parameters. They name the values the method passes into the block.

Some methods pass one value, others pass several. each passes one element at a time:

[10, 20, 30].each { |n| puts n }

each_with_index passes two, the element and its index:

["a", "b", "c"].each_with_index do |letter, i|
  puts "#{i}: #{letter}"
end
# 0: a
# 1: b
# 2: c

When iterating a hash, the block parameters are key and value:

{ a: 1, b: 2 }.each do |key, value|
  puts "#{key} = #{value}"
end

The number and order of block parameters depends on what the method yields. When in doubt, check the docs or try one parameter and see what you get.

challenge icon

Challenge

Easy

The hash scores is given. Iterate it with each_with_index on its to_a form so you have access to both the (name, points) pair and its position. Print one line per entry in this format:

<rank>. <name> - <points>

Where rank starts at 1 (not 0).

For the default hash the output is:

1. Alice - 90
2. Bob - 85
3. Cara - 78

Cheat sheet

Block parameters are named between pipes |...| and receive values yielded by the method:

# each – one parameter
[10, 20, 30].each { |n| puts n }

# each_with_index – element and index
["a", "b", "c"].each_with_index do |letter, i|
  puts "#{i}: #{letter}"
end

# hash each – key and value
{ a: 1, b: 2 }.each do |key, value|
  puts "#{key} = #{value}"
end

hash.to_a converts a hash to an array of [key, value] pairs, useful with each_with_index:

{ a: 1, b: 2 }.to_a.each_with_index do |(key, value), i|
  puts "#{i}: #{key} = #{value}"
end

Try it yourself

scores = { "Alice" => 90, "Bob" => 85, "Cara" => 78 }

# TODO: print "<rank>. <name> - <points>" for each entry, rank starts at 1
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow