内置Ruby方法

tjh*_*hnc 6 ruby methods

如果有一个定义的内置ruby方法,是否总是更喜欢使用内置方法?

如果我有以下代码:

if i == 0
Run Code Online (Sandbox Code Playgroud)

相反使用内置的ruby方法有什么好处?

if i.zero?
Run Code Online (Sandbox Code Playgroud)

fal*_*tru 5

i.zero?只能如果iNumeric对象.

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>'
Run Code Online (Sandbox Code Playgroud)


Мал*_*евъ 2

我写了一个简单的测试:

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
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,:zero?method 相对于 method 需要一些额外的时间(大约 10%):==,所以它比:==. 其次,由于:zero?方法仅包含在Numeric类及其后代中,因此您只能在数字上使用它。