Casting to an Integer
suggest change"123.50".to_i #=> 123
Integer("123") #=> 123
Integer is stricter than to_i. Integer("123.50") raises ArgumentError because the string is not a whole integer.
to_i reads an integer from the start of a string and ignores the rest. It does not look for an integer later in the string:
"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"
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents