Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.)