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 Ruby Blocks Ruby Blocks Write a Block Method

Ron Chan
Ron Chan
10,987 Points

Why create blocks in ruby...

when you can instead create another method? Are there some situations where creating a block might be better idea than creating another method?

1 Answer

Brandon Barrette
Brandon Barrette
20,485 Points

You will see soon in later videos that you might yield to a block (meaning passing a block into a method), something you couldn't do with two methods. Think of a block as bits of ruby code (to be executed), rather than arguments which are values. I wouldn't be able to pass in bits of ruby code as an argument to a method.

Read more here: http://www.tutorialspoint.com/ruby/ruby_blocks.htm

Specifically:

def hello
  puts "Hello"
  yield
end


hello { puts "World" }
=> Hello World
hello { puts "how are you today?"}
=> Hello how are you today?

You can also do:

def hello(name, &block)
  puts "Hello #{name}"
  block.call
end


hello("World") { puts "How are you?" }
=> Hello World
=> How are you?

Notice here I can pass in a block, which can be useful to pass other pieces of code into a method, something you can NOT do with arguments.

lindseyk
lindseyk
4,506 Points

Is this sort of like the flexibility of branching, in that you can have a method that will do something different in different scenarios/cases? (I'm trying to wrap my head around when you would use this, vs writing the block as part of the method to begin with, or using if, else, etc.)