A zero on a sign on the wall

Bernard Hermant

Use zero? for comparison of numerics like Integer, Float and BigDecimal

Compared to other similar languages, Ruby often prioritises readability (and joy) when it comes to its syntax and the methods provided in its Standard Library.

An example of this is the syntactic sugar used when comparing a value to zero.

Take a look at the documentation for the .zero? method on Integer, Float, Numeric and BigDecimal.

Instead of…

…checking whether a value is equal to 0 in a conditional:

if number == 0
  :yes
else
  :no
end

Use…

…the built-in #zero? method on all numeric types:

if number.zero?
  :yes
else
  :no
end

Why?

The Ruby-ish syntax is clearer and less error prone.

In the first example, it is very easy to mistakenly type number = 0 and thus assign a variable in the conditional rather than perform a comparison (although you might use tests to protect yourself from that particular error).

Why not?

The == 0 syntax is how many other similar languages perform comparisons and is deeply ingrained for many of us. I still struggle to apply this advice even after 15 years of Ruby programming.

You might get some folks pushing back for “performance” reasons.

require "benchmark/ips"

Benchmark.ips do |x|
  x.report("1 == 0") { 1 == 0 } #=> false
  x.report("0 == 0") { 0 == 0 } #=> true
  x.report("1.zero?") { 1.zero? } #=> false
  x.report("0.zero?") { 0.zero? } #=> true

  x.report("1.0 == 0") { 1.0 == 0 } #=> false
  x.report("0.0 == 0") { 0.0 == 0 } #=> true
  x.report("1.0.zero?") { 1.0.zero? } #=> false
  x.report("0.0.zero?") { 0.0.zero? } #=> true
end

For Integer:

1 == 0 29.049M (± 0.7%) i/s
0 == 0 28.972M (± 0.3%) i/s
1.zero? 23.009M (± 1.0%) i/s
0.zero? 22.860M (± 1.7%) i/s

For Float:

1.0 == 0 18.768M (± 2.0%) i/s
0.0 == 0 19.066M (± 0.5%) i/s
1.0.zero? 22.784M (± 0.6%) i/s
0.0.zero? 22.841M (± 0.8%) i/s

The benchmark shows that for Integers the == syntax is faster, but for Floats the .zero? syntax wins out.

However, the important thing to note is that in all cases you still get millions of executions per second, so in your code you should emphasise the readability over any perceived performance implications!

Sign up to get a nugget of Ruby knowledge every couple of weeks or so.

Last updated on October 31st, 2022