Ruby 2.6 adds exception parameters for Integer & Float methods

Prathamesh Sonpatki

By Prathamesh Sonpatki

on 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.

1
2> > "1one".to_i
3> > => 1
4
5> > Integer("1one")
6> > ArgumentError: invalid value for Integer(): "1one"
7
8    from (irb):2:in `Integer'
9    from (irb):2
10    from /Users/prathamesh/.rbenv/versions/2.4.0/bin/irb:11:in `<main>'
11
12> >

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.

1
2> > Integer("msg") rescue nil
3> >

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.

1
2> > Float("foo", exception: false)
3> > => nil
4> > Integer("foo", exception: false)
5> > => nil
6> >

This is also faster than rescuing the exception and returning nil.

1
2> > Benchmark.ips do |x|
3> > ?> x.report("rescue") {
4> > ?> Integer('foo') rescue nil
5> > }
6> > x.report("kwarg") {
7> > ?> Integer('foo', exception: false)
8> > }
9> > x.compare!
10> > end
11> > Warming up --------------------------------------
12
13              rescue    41.896k i/100ms
14               kwarg    81.459k i/100ms
15
16Calculating -------------------------------------
17rescue 488.006k (± 4.5%) i/s - 2.472M in 5.076848s
18kwarg 1.024M (±11.8%) i/s - 5.050M in 5.024937s
19
20Comparison:
21kwarg: 1023555.3 i/s
22rescue: 488006.0 i/s - 2.10x slower
23
24

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.

1
2> > Integer('foo') rescue 42
3> > => 42
4> >

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.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.