Ryan Haining Ryan Haining - 2 months ago 19
Ruby Question

Convert string to Float or Fixnum

Given a string from user input, I want to convert it to a

Fixnum
or
Integer
if the string is a valid int. I do not want to convert to an int if the string is a float. If that fails, I then want to try to convert the string to a
Float
. If the string is not either of these I intend to just raise an exception.

It seems that
String#to_i
just truncates any
Float
value rather than providing any sort of error. I know I could do some regexing to determine whether a
String
is a valid int, but it seems like there should be some built-in conversion that fails if a
String
has anything other that digits. Am I missing something?

For example. I want something like this that fails instead of returning
1


irb(main):092:0> "1.4".to_i
=> 1
irb(main):093:0> "1.4e5".to_i
=> 1

Answer
def int_then_float string
  Integer(string)
rescue ArgumentError
  Float(string)
end