Ruby to_i

.to_i is frequently used to convert a string value to an integer. This method has a couple tricks up it’s sleeve. And if all the tricks fail, it returns zero instead of an exception.

last_order = "10"
next_order_number = last_order.to_i + 1

address = "10B".to_i # returns 10
distance = "100km".to_i # returns 100

invoice_number = "ooops".to_i # returns 0

However, the alternative way to convert to integer, Integer isn’t quite so easy going. But it has some tricks too; it can take base as argument.

address = Integer("10B") # ArgumentError (invalid value for Integer(): "10B")
Integer('111',2) # returns 7, as 2 indicates base 2
Integer('0x100') # returns 256
'0x100'.to_i # returns 0