Menu

Ruby Blocks and yield Explained with the Simplest Examples
πŸ“°

Ruby Blocks and yield Explained with the Simplest Examples

DEV Community: rubyΒ·KaziuΒ·about 3 hours ago
#1LdrBZKA
#devtoruby#devto#dev#yield#enter
Reading 0:00
15s threshold

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?…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.