Reputation: 143
If there is a defined built in ruby method, is it always preferable to use the built-in method?
If I have code such as:
if i == 0
What is the advantage to instead using the built-in ruby method?
if i.zero?
Upvotes: 6
Views: 449
Reputation: 110725
I've made a New Year's resolution to make greater use of Ruby methods that end with a question mark. I think doing do so will make my code more expressive and also cut down on errors. The most obvious example of the latter is using eql?
instead of ==
(for comparing objects of class Object
, not to be confused with equal?
). But how often do you see x.eql? 7
instead of x == 7
? Probably less often than you see x = 7
, when x == 7
was intended.
Some others that seem to get less respect than they deserve include (the afore-mentioned) zero?
, nonzero?
, integer?
, empty?
, any?
, all?
, nil?
, none?
, one?
, start_with?
and end_with?
.
Upvotes: 0
Reputation: 369274
i.zero?
works only if i
is Numeric
object.
i = nil
i == 0
# => false
i.zero?
# NoMethodError: undefined method `zero?' for nil:NilClass
# from (irb):5
# from C:/Ruby200-x64/bin/irb:12:in `<main>'
Upvotes: 5
Reputation: 16505
I've written simple test:
require 'benchmark'
l = 0
funcs =
[ proc { l == 0 },
proc { l.zero? },
]
def ctime func
time = 0
1000.times { time += Benchmark.measure { 1000.times { func.call } }.to_a[5].to_f }
rtime = time /= 1000000
end
funcs.each {| func | p ctime( func ) }
# 4.385690689086914e-07
# 4.829726219177246e-07
As you can see :zero?
method takes a few additional time (about 10%) against the :==
method, so it is slower than :==
. Second, since :zero?
method is included only in Numeric
class and its descendants, you can use it only on numbers.
Upvotes: 2
Reputation: 59303
As far as I know, those kinds of methods are for doing something like:
array.delete_if &:zero?
It may be preferable to use == 0
in if statements and such for consistency, but this is now more of a matter of opinion.
If you think zero?
is more readable, use it.
Upvotes: 2