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 trial

Ruby Ruby Loops Build a Simple Contact List Part 3: Printing The Contact List

Eylon Cohen
Eylon Cohen
4,779 Points

Abount numbers and strings

One of the methods in this video was:

def ask(question, kind="string")
  print question + " "
  answer = gets.chomp
  answer = answer.to_i if kind == "number"
  return answer
end

if the answer is a number, does it change the value of the varible kind? does "number" means a number? I thought that what is between " " is the content of the string...

3 Answers

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

In this particular code, since you're not changing the variable number at any point, it is always "string", so answer = answer.to_i if kind == "number" never gets executed. Which means that whatever you enter, will remain a string.

However, if you call this method and pass 'number' as the second argument, it will convert whatever you enter into an integer (to_i).

Eylon Cohen
Eylon Cohen
4,779 Points

This is what I had in mind, but in the code presented, there is no second argument:

phone = ask("Enter a phone number:")

This means the kind stays "string". .... what am I getting wrong?

Maciej Czuchnowski
Maciej Czuchnowski
36,441 Points

Yeah, and it will remain a string - you should store phone numbers as strings, since they can sometimes contain things like + or (), spaces etc. For example:

(+48) 123 152 555 - you can't store that as an integer.

I guess Jason added this additional type of input to potentially allow the user to have more contact info. And perhaps on of those would need to be an integer, executed as ask("what's your age?", "number").

Eylon Cohen
Eylon Cohen
4,779 Points

I see. ok, Thanks!