A.12 Blocks
A.12.1 .times
Integer#times do
# ruby code here
end
⇒ Integer
or
Integer#times do |Integer|
# ruby code here
end
⇒ Integer
The .times method takes a Block as an argument and will execute the code within that block the number of times specified by the integer. A Block of code is the code written in between the keywords do and end. This looping method returns an Integer of the number of times the loop ran.
10.times do
p "Hi"
endThe above block of code will print “Hi” 10 times all on newlines.
To keep a track of the iteration number, .times can create a block variable that starts of counting the iteration number starting at zero. After each execution of the code within the block, the block variable is incremented by 1.
10.times do |counter|
p counter
endThe above block of code will print the numbers 0 to 9 all on newlines.
A.12.2 .upto
Integer#upto do |Integer|
# ruby code here
end
⇒ Integer
The upto method takes the first Integer the method is called on and uses it to initialize the value of
the block variable. The second Integer becomes the stopping condition to the loop as the block variable’
increases by one after each iteration. The method returns an Integer; the initial value of the block variable.
5.upto(10) do |counter|
# do something
endThe above block of code starts the block variable counter at 5 and executes the block until counter is 10.
A.12.3 .downto
Integer#downto do |Integer|
# ruby code here
end
⇒ Integer
The downto method takes the first Integer the method is called on and uses it to initialize the value of
the block variable. The second Integer becomes the stopping condition to the loop as the block variable’
decreases by one after each iteration. The method returns an Integer; the initial value of the block variable.
10.downto(5) do |counter|
# do something
endThe above block of code starts the block variable counter at 10 and executes the block until counter is 5.
A.12.4 .step
Integer#step(Integer, Integer) do |Integer|
# ruby code here
end
⇒ Integer
The step method initializes the block variable to be the value of the Integer that called the method. The first Integer argument is the the value the block variable is when the loop will stop. The last Integerargument is what value to modify the block variable after each iteration. This method returns the Integer that called the method.
1.step(10, 3) do |counter|
p counter
end1
4
7
10
The above block of code starts the block variable counter at 1 and executes the block until counter is 10 but after each iteration the counter will be incremented by 3 instead of 1. .step can also be used to decrement the counter by a certain value.
10.step(1, -4) do |counter|
p counter
end10
6
2