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: cWhen iterating a hash, the block parameters are key and value:
{ a: 1, b: 2 }.each do |key, value|
puts "#{key} = #{value}"
endThe 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
EasyThe 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 - 78Cheat 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}"
endhash.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}"
endTry it yourself
scores = { "Alice" => 90, "Bob" => 85, "Cara" => 78 }
# TODO: print "<rank>. <name> - <points>" for each entry, rank starts at 1
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Strings In Depth
String Methods OverviewString InterpolationIterating Over StringsSplit and JoinRecap - String Weaver4Blocks, Procs & Lambdas
What is a Block?do..end vs BracesThe yield KeywordBlock ParametersProcs and LambdasRecap - Custom Iterator7Hashes Part 2
Hash.new with DefaultsIterating HashesNested HashesMerging and TransformingRecap - Frequency Counter10Project - Student Records
Project OverviewAdd Student5Enumerable Powerhouse
Select and RejectChaining MapReduce / Injectcount, all?, any?, none?group_by and partitionsort_by, min_by, max_byRecap - Data Pipeline8Advanced Decision Making
Case with Classes & RegexMulti-value whenTernary OperatorInline if / unlessRecap - Grade Classifier