If you write Ruby, you'll always run into "blocks" and "yield."
They look tricky, but really it's just "passing some code" and "running the code you were passed."
What's a block?
It's a "chunk of code (a little snippet)" you pass to a method .
You wrap it in { } or do...end .
[ 1 , 2 , 3 ] . each { | n | puts n } # ββββββββββββ this is the block
Enter fullscreen mode
Exit fullscreen mode
You're handing .each a set of instructions saying "do puts n for each element."
1 2 3
Enter fullscreen mode
Exit fullscreen mode
{ } and do...end are the same thing. You just use do...end when it gets long.
[ 1 , 2 , 3 ] . each do | n | puts n end
Enter fullscreen mode
Exit fullscreen mode
What's yield?
It's an instruction that runs the passed-in block at "the spot where you wrote yield" inside the method .
def greet puts "Hello" yield # β run the passed-in block here puts "Goodbye" end
greet { puts "How are you?" }
Enter fullscreen mode
Exit fullscreen mode
Hello How are you?β¦