Built-in Ruby Methods

If there is a specific ruby ​​built-in method, is it always preferable to use the built-in method?

If I have code, for example:

if i == 0 

What is the advantage of using the built-in ruby ​​method?

 if i.zero? 
+6
source share
4 answers

I wrote a 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, the method :zero? It takes several additional (about 10%) methods against the method :== , so it is slower than :== . Secondly, since the method :zero? only included in the Numeric class and its descendants, you can use it only for numbers.

+2
source

i.zero? only works if i is a 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>' 
+5
source

As far as I know, these methods are designed to do something like:

 array.delete_if &:zero? 

It may be preferable to use == 0 in if expressions and such for consistency, but now it depends more on the opinion.

If you think that zero? more readable, use it.

+2
source

I adopted the New Year's resolution to make more use of Ruby methods that end with a question mark. I think doing this will make my code more expressive and also reduce the number of errors. The most obvious example of the latter is eql? instead of == (to compare objects of class Object , so as not to be confused with equal? ). But how often do you see x.eql? 7 x.eql? 7 instead of x == 7 ? Probably less often than you see x = 7 when x == 7 assumed.

Some others that seem to get less respect than they deserve include (mentioned above) zero? nonzero? integer? empty? , any? , all? , nil? , none? one? start_with? and end_with? .

0
source

All Articles