We can use
Float methods to convert values to integers
and floats respectively.
Ruby also has
to_f methods for same purpose.
Let’s see how it differs from
to_i method tries to convert the given input to integer
as much as possible
Integer method throws an
if it can’t covert the input to integer.
Float methods parse more strictly
Some times, we might need the strictness of
but ability to not raise an exception every time the input can’t be parsed.
Before Ruby 2.6 it was possible to achieve it in following way.
In Ruby 2.6,
the Integer and Float methods accept a keyword argument exception
which can be either
If it is
false then no exception is raised if the input can’t be parsed
nil is returned.
This is also faster than rescuing the exception and returning
As we can see, rescuing the exception is twice slower
than using the new keyword argument.
We can still use the older technique
if we want to return a different value from
the keyword argument
exception is set to
for backward compatibility.
The Chinese version of this blog is available here.