What is a Block?
Part of the Logic & Flow section of Coddy's Ruby journey — lesson 15 of 56.
You've already been writing blocks. Every time you wrote each do |x| ... end, the part between do and end was a block: a chunk of code passed to a method.
[1, 2, 3].each do |n|
puts n * 2
endHere, each is a method on the array, and do |n| ... end is the block. each runs the block once for every element, passing it in as n.
Blocks are not separate objects you store in variables, they're tied directly to the method call. A method either gets a block or doesn't, and most iteration methods (each, map, select, times) are designed to take one.
3.times do |i|
puts "hi #{i}"
endCalling a method without its block changes what it does. [1,2,3].map with no block returns an enumerator instead of a transformed array, so the block is part of what the method means.
Challenge
BeginnerRead an integer n from input. Use the times method with a block to print the message Iteration <i> for each value of i from 0 up to n - 1.
For input 3, the output is:
Iteration 0
Iteration 1
Iteration 2Cheat sheet
A block is a chunk of code passed to a method between do |param| ... end:
[1, 2, 3].each do |n|
puts n * 2
endUse times to repeat a block n times, with i going from 0 to n - 1:
3.times do |i|
puts "hi #{i}"
endTry it yourself
n = gets.to_i
# TODO: use n.times with a block to print each iteration
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