浏览 5440 次
锁定老帖子 主题:Ruby中判断奇偶数最简单最效率的办法
精华帖 (0) :: 良好帖 (7) :: 新手帖 (0) :: 隐藏帖 (12)
|
|
---|---|
作者 | 正文 |
发表时间:2008-03-17
def even?(value) value[0]!=1 end even?(10) #true even?(11) #false 这下好了,连&都不用写了。 可能有点吹毛求疵~权当娱乐 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2008-03-17
active_support提供这样的实现了。
|
|
返回顶楼 | |
发表时间:2008-03-17
def even2?(value)
value & 1 == 0 end 这个仿佛要快一点点。我用benchmark跑了一下,跑15秒左右的数据大概少用0.5秒。不过不知道准不准,也不知道这点差异是否有效。 |
|
返回顶楼 | |
发表时间:2008-03-17
active_support的even_odd.rb扩展了数值类型,源码全文是:
module ActiveSupport #:nodoc: module CoreExtensions #:nodoc: module Integer #:nodoc: # For checking if a fixnum is even or odd. # * 1.even? # => false # * 1.odd? # => true # * 2.even? # => true # * 2.odd? # => false module EvenOdd def multiple_of?(number) self % number == 0 end def even? multiple_of? 2 end if RUBY_VERSION < '1.9' def odd? !even? end if RUBY_VERSION < '1.9' end end end end ruby1.9加了Integer#odd?, #even?,所以它在里面做了判断。 Fixnum#[]原来是位操作: 引用 Bit Reference---Returns the nth bit in the binary representation of fix, where fix[0] is the least significant bit.
|
|
返回顶楼 | |