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 1: Asking Questions

Thomas Salai
Thomas Salai
4,964 Points

Why do we check number in as a String ?

Why do we check here if kind == as a String in double quote! ? Do we check here answer(which is from uswer input) is Numeric Type or NOT ?

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

answer = ask("What is your name?")
puts answer
answer = answer.to_i if kind == "number"
this line and 
answer = answer.to_i if kind == "number"
this line are same ?
answer = answer.to_i if answer.is_a?(Numeric)

this comparison with String value "number" make me confusions. Can anybody explain me here why we do this and how Ruby interpret the comparison == "number".

many thanks in advance.


2 Answers

hi there, It is always a question why we check number in as a String ?

For example when i am checking numeric or not am expecting as below results

"34" =>  true
34 => true
"34sdfds" => it should return false
34.90 =>  false
"34.90" => false

This is very helpful article; http://mentalized.net/journal/2011/04/14/ruby-how-to-check-if-a-string-is-numeric/

happy coding :)

rowend rowend
rowend rowend
2,926 Points

Well, let me say this: The ask method get 2 arguments. The first argument question is not optional. The second argument kind is optional and have a default value 'string'. This means you can call your method like:

ask('what is your name?') in this case the method will no do the integer conversion.
ask('waht is your age?', 'number') in this case the method will do the integer conversion.

I hope this help you.