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

Thomas Salai
Thomas Salai
4,389 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

ellie adam
ellie adam
26,376 Points

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.