Ruby Notes - Ruby blocks
What is it?
A code block is a chunk of code you can pass to a method, as if the block were another parameter.
What does it look like?
foo.each { puts "hello"}
foo.each do
puts "hello"
end
animals = ["ant", "bee", "cat", "dog"]
animals.each { |animal| puts animal }
5.times { print "*" }
3.upto(6) { |i| print i }
("a".."e").each { |char| print char }
("a".."e").each { print _1 }
greet { puts "Hi" }
verbose_greet("Dave", "loyal customer") { puts "Hi"}
How does a method call the block code?
Using the yield
statement
def verbose_greet (name, greeting)
puts "Start method"
yield(name, greeting)
puts "End method"
end
verbose_greet("Dave", "hello") { |person, greet| puts "#{person} #{greet}"}
# outputs
# Dave hello
Anything weird to remember?
-
Method parameters appear before the block.
-
You can pass only one block per method call.
-
The
yield
statement invokes the block.