1

In Ruby - I want to prompt a user but have the response be evaluated and if not returned as an Integer have it reply as such. It doesn't seem to be working.

print ('what is your age:    ')
age = gets

if age.is_a?(Integer)
  puts ("your age is #{age}")
else
  puts ("you need to use a number!")

end
Ank
  • 1,864
  • 4
  • 31
  • 51
codeclimb
  • 11
  • 6
  • 2
    The result of `gets` is a String. – steenslag Sep 14 '17 at 16:14
  • 1
    Not related to your problem, but don't put a space between the method name and the parentheses. Either put the parentheses right after the method name, i.e. `puts("...")` or omit them, i.e. `puts "..."` – Stefan Sep 14 '17 at 16:26
  • You might be tempted to use `to_i` on the age, but this won't work as expected because `"hello".to_i` is 0. See [test-if-a-string-is-basically-an-integer-in-quotes-using-ruby](https://stackoverflow.com/questions/1235863/test-if-a-string-is-basically-an-integer-in-quotes-using-ruby) – max pleaner Sep 14 '17 at 16:27
  • I do not close this answer as a duplicate to the linked one, since the linked suggests monkeypatching (mostly because it’s dated 2009.) – Aleksei Matiushkin Sep 14 '17 at 16:40
  • The acceptable solution in that particular case would be: `age = Integer(gets) rescue nil`. It permits spaces _around_ the input, including CRLF, that is implicitly existing in what `gets` returns. – Aleksei Matiushkin Sep 14 '17 at 16:43
  • @mudasobwa when you suppress an exception to assign `nil` to `age` in order to have a type check afterwards, aren't you (mis)using exceptions for control flow? ;-) – Stefan Sep 14 '17 at 17:05
  • 2
    @Stefan I am, but it’s still a way better (and three ways faster) than regex. I am not a big fan of how `Kernel#Integer()` throws an exception instead of returning `nil`, so I would blame Matz&Co° for (mis)using exceptions for the control flow :) – Aleksei Matiushkin Sep 14 '17 at 17:09

0 Answers0