morrime morrime - 16 days ago 5
Ruby Question

Ruby How to convert string to integer without .to_i

Is there a way to output an integer given a string containing numbers between 0 and 9. For example, input is "219", output would be 219, and you can't use .to_i

Answer

You can use Kernel::Integer:

Integer("219")
  #=> 219 
Integer("21cat9")
  # ArgumentError: invalid value for Integer(): "21cat9"

Sometimes this method is used as follows:

def convert_to_i(str)
  begin
    Integer(str)
  rescue ArgumentError
    nil
  end
end

convert_to_i("219")
  #=> 219
convert_to_i("21cat9")
  #=> nil
convert_to_i("1_234")
  #=> 1234
convert_to_i("  12  ")
  #=> 12 
convert_to_i("0b11011") # binary representation
  #=> 27 
convert_to_i("054")     # octal representation
  #=> 44
convert_to_i("0xC")     # hexidecimal representation
  #=> 12 

Some use an "inline rescue" (though it is less selective, as it rescues all exceptions):

def convert_to_i(str)
  Integer(str) rescue nil
end

There are similar Kernel methods to convert a string to a float or rational.