0

I have the following code in my irb:

irb(main):005:0> num = gets.chomp.to_i
,
=> 0
irb(main):006:0> num.is_a? Integer
=> true
irb(main):007:0> num = gets.chomp.to_i
q
=> 0
irb(main):008:0> num.is_a? Integer
=> true

I'm really new to ruby and i wonder, why "q" an "," is here an Integer... Could you please explain me why?

phd
  • 819
  • 1
  • 7
  • 11
  • @maicher Please have a look here.. http://stackoverflow.com/questions/4589968/ruby-rails-how-to-check-if-a-var-is-an-integer#4589985 – phd Jun 25 '15 at 21:12
  • [Here](http://ruby-doc.org/core-2.2.0/String.html#method-i-to_i) you can read what String#to_i method actually does. Hope it helps. – codevolution Jun 25 '15 at 21:09
  • Yes! Thank you! :) Do you know how i could use an other method which makes sure that the if statement only executes if it's an integer? – phd Jun 25 '15 at 21:17
  • `Integer(",")` will raise an ArgumentError. – zetetic Jun 25 '15 at 21:21
  • gets method returns string or nil, so there is no way to have an instance of Integer as a result. If you want to be sure that your input is a type of Integer, you could do @zetetic's trick (check = Integer(gets.chomp) rescue false). If an input is an Integer the right side will return the integer (which is other than nil & false, so the if condition will pass), if not it will raise an error and return false (if condition will not pass). – codevolution Jun 25 '15 at 21:37

2 Answers2

4

This is the documentation of String.to_i.

Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception when base is valid.

As documented, any string where the leading character is not a valid digit, is still converted into an Integer, specifically into 0.

",".to_i == 0
# => true

Clearly, 0 is an Integer.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • Thank you. I found that out in the docs. is there another possible way to check if an input is an Integer? – phd Jun 25 '15 at 21:38
  • Simply use a regular expression: `/\A\d+\z/.match(num)` where `num` is your input. Keep in mind that you can check if the input is formally valid, but then if you want to use the input as integer you have to convert it since input from keyboard is always a String. – Simone Carletti Jun 25 '15 at 21:55
0

As others have pointed out String.to_i will convert the string to it's integer counterpart. If a suitable conversion can't be done (i.e. it consists of only a ,) then 0 will be returned.

If you wanted to conditionally do something if the input was an integer you could do something like:

if number = Integer(gets.chomp) rescue nil
  puts "We have an integer!"
else
  puts "No Integer here...move along"
end
Kyle Decot
  • 20,715
  • 39
  • 142
  • 263