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 trialDylan Barnard
1,860 PointsWe don't need a block argument here?
I think the example in this video might be too simplistic, because we actually don't need a lot of the code the instructor is using to get the program to run. Here is my code snippet which is missing several components but still runs: 1) the block argument - |name| 2) yield name
def get_name
puts "Enter your name"
name = gets.chomp
end
get_name do
puts "That's a cool name, #{name}"
end
Can anyone give an example where you actually need block arguments and yield to get a more complex piece of code to run?
2 Answers
Rodrigo Castro
15,652 PointsHi Dylan,
I tried to run this piece code, and what I noticed is that the code runs because here
get_name do puts "That's a cool name, #{name}" end
the program simply calls the method, which just asks for the user input, however, if you want to print the string inside the block you actually have to use the yield, which would call the block and require the 'name' parameter, otherwise it would display an error.
Gustavo Zimmermann
6,857 Pointsbear in mind, that block arguments is a tool, you can use it, or you can find other means to do a job, so its hard to say that you need to use it. So better than a code example is to think what kind of problem can be solved using that tool. And the example that i give you is: imagine you are creating a class that work in all the files in a given directory, Its a generic class, and you will use in several different programs. You want to be able to show the progress of the work, but that is not your business, you dont even know witch program will be running, so you give the chance to who ever call you to show the progress yielding to a block that will know how to show things to the user. did this answer your question?