July 31, 2018
This blog is part of our Ruby 2.6 series.
We can use Integer
and Float
methods to convert values to integers and
floats respectively. Ruby also has to_i
and to_f
methods for same purpose.
Let's see how it differs from the Integer
method.
> > "1one".to_i
> > => 1
> > Integer("1one")
> > ArgumentError: invalid value for Integer(): "1one"
from (irb):2:in `Integer'
from (irb):2
from /Users/prathamesh/.rbenv/versions/2.4.0/bin/irb:11:in `<main>'
> >
The to_i
method tries to convert the given input to integer as much as
possible whereas the Integer
method throws an ArgumentError
if it can't
covert the input to integer. The Integer
and Float
methods parse more
strictly compared to to_i
and to_f
respectively.
Some times, we might need the strictness of Integer
and Float
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.
> > Integer("msg") rescue nil
> >
In Ruby 2.6, the
Integer and Float methods accept a keyword argument exception
which can be either true
or false
. If it is false
then no exception is
raised if the input can't be parsed and nil
is returned.
> > Float("foo", exception: false)
> > => nil
> > Integer("foo", exception: false)
> > => nil
> >
This is also faster than rescuing the exception and returning nil
.
> > Benchmark.ips do |x|
> > ?> x.report("rescue") {
> > ?> Integer('foo') rescue nil
> > }
> > x.report("kwarg") {
> > ?> Integer('foo', exception: false)
> > }
> > x.compare!
> > end
> > Warming up --------------------------------------
rescue 41.896k i/100ms
kwarg 81.459k i/100ms
Calculating -------------------------------------
rescue 488.006k (± 4.5%) i/s - 2.472M in 5.076848s
kwarg 1.024M (±11.8%) i/s - 5.050M in 5.024937s
Comparison:
kwarg: 1023555.3 i/s
rescue: 488006.0 i/s - 2.10x slower
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 nil
.
> > Integer('foo') rescue 42
> > => 42
> >
By default, the keyword argument exception
is set to true
for backward
compatibility.
The Chinese version of this blog is available here.
If this blog was helpful, check out our full blog archive.