Casting to an Integer

Download ruby eBook


"123.50".to_i     #=> 123
Integer("123.50") #=> 123

A string will take the value of any integer at its start, but will not take integers from anywhere else:

"123-foo".to_i # => 123
"foo-123".to_i # => 0

However, there is a difference when the string is not a valid Integer:

"something".to_i     #=> 0
Integer("something") # ArgumentError: invalid value for Integer(): "something"


Contributors: 4
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial:

Download eBook