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 Loops Build a Simple Contact List Part 2: Adding Contacts

hamza razzak
PLUS
hamza razzak
Courses Plus Student 2,782 Points

How 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
warborn
7,116 Points

Hi! 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
William Bode
7,105 Points

Hi,

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.