ruby酷酷的方法——另一种next
irb(main):022:0* 1.next => 2 irb(main):023:0> "a".next => "b" irb(main):024:0> "1".next => "2" irb(main):025:0>
性能比较:
require 'benchmark' n=(1..1000000).to_a def num_next(first,last) while first != last first=first.next end end def num_join(first,last) while first != last first+=1 end end Benchmark.bm do |bm| bm.report("each") do n.each do |d| d end end bm.report("next") do num_next(1,1000000) end bm.report(" + ") do num_join(1,1000000) end end
输出: user system total real each 0.219000 0.000000 0.219000 ( 0.218000) next 0.266000 0.000000 0.266000 ( 0.266000) + 0.312000 0.000000 0.312000 ( 0.313000)
性能还不错,向ruby脱帽致敬!!