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 trialhamza razzak
Courses Plus Student 2,782 PointsHow does ruby know which method to run first if two methods have been declared in the contact_list.rb file?
When we run ruby contact_list.rb... how does ruby know which method to run? Which method is run ... Im confused. Secondly why is the following snippet outside both methods?
answer = ""
while answer != "n"
contact.push(add_contact())
answer = ask("Do you want to add another? (y/n)")
end
Can you provide a step by step execution steps please?
2 Answers
warborn
7,116 PointsHi! the answer to your question stands in the difference between declaring a method and calling it, declaring is to let ruby know about that method exists and what it does, calling a method is the way you execute the code that is inside.
Think in a method as a way to group code with a name, so you can use it (call it) whenever you want, for example in the code snippet is where you call both methods declared before, is where the code inside them executes, in this case for add a new contact and to ask to the user if wants to add another, the code snippet it's outside to be able to call the methods.
The code between the "def - end" is the method declaration, and when you write the name like in "add_contact()" is where you made a call to the method and his code is executed, sorry for bad english.
William Bode
7,105 PointsHi,
Ivan's answer is good, but I will try to explain this more easy to understand:
When you define a method "do_something" with "def do_something....end", you just write down the instructions for your computer. When you call the method with "do_something()", you tell your computer to act upon these instructions.
Ruby runs the instructions in order of you calling them.