Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

Richard McGrath
Richard McGrath
5,597 Points

How come a puts statement will be executed first if not in the block or block method but placed between them?

def block_method
  puts "This is the first line in block_method"
  yield
  puts "This statement is after the yield keyword"
end

puts "This statement is physically located between the method and block"

block_method do
  puts "This statement is called from the block"
end

The output I get from running the following code is:

  • This statement is physically located between the method and block
  • This is the first line in block_method
  • This statement is called from the block
  • This statement is after the yield keyword

2 Answers

Kourosh Raeen
Kourosh Raeen
23,733 Points

Because the first five lines of code are only defining the method. You are calling the block_method method after the line:

puts "This statement is physically located between the method and block"

So the very first thing that gets printed is: "This statement is physically located between the method and block"

All other puts statements get executed once the method is actually called, which is here:

block_method do
  puts "This statement is called from the block"
end
Richard McGrath
Richard McGrath
5,597 Points

This makes sense now, thank you.