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 trialBoris Baskovec
4,798 PointsWhy do you use the do method?
What is the difference between
paper = Paper.new do |p|
p.title "Awesome paper"
p.heading "This is my paper"
p.body "Youhou"
end
paper.display
AND
p = Paper.new
p.title "Awesome paper"
p.heading "This is my paper"
p.body "Youhou"
p.display
I would have used the second way to do it, the only difference is that you can use the "p" inside the do method and then use the full name of the variable outside?
Alex Bishop
4,817 PointsAlex Bishop
4,817 PointsWell, to start, the do and end syntax are just another way of defining that the following text will be a block of code, just like curly braces ( {} ). The main difference between using these two syntaxes however is that curly braces have a higher priority in the ruby interpreter than do and end have in the interpreter. You can see mentioned in the first section of the Ruby Foundations - Blocks video here: http://teamtreehouse.com/library/ruby-foundations/blocks/creating-blocks
The difference from what I can see is minute and you can use whatever syntax you want for Ruby (one of the great things about the language), you will only have to worry about this in more complicated code. I think Jason just uses this syntax here to continue to show us the many syntaxes you see when new instances of classes are created in ruby. Your code will work in this program, but you should try to keep your syntax for these things as neat and readable as possible for the ease of other programmers looking at your work, the same reason you should use lots of notes explaining how things work. For example, I like to use curly braces, and I would of defined the code like this:
This is again, up to you, and may not have any problems in the interpreter unless the code is complicated and the ordering is very important in the program you execute. Do what you feel is comfortable if it works and doesn't cause problems in the code. I'm still learning Ruby myself, but I hope this helps!