From: SASADA Koichi Date: 2009-02-26T05:16:41+09:00 Subject: [ruby-dev:38085] Re: [Feature:trunk] nested loop construct Yukihiro Matsumoto wrote:: > def nloop(*args, &block) > helper = ->(args, buf, offset, block) { > limit = args[offset] > if (offset+1 == args.size) > limit.times do|i| > buf[offset] = i > block.yield *buf > end > else > limit.times do|i| > buf[offset] = i > helper.(args, buf, offset+1, block) > end > end > } > helper.(args, [], 0, block) > end  うわー,はじめてみました. -> とか .() とか. def nloop *args str = '' h = lambda{|i| next "yield #{(0...i).map{|e| "v#{e}"}.join(', ')}\n" \ if args.length == 0 str << "v#{i} = 0; while v#{i} < #{args.shift}\n" str << h.call(i+1) str << "v#{i} = v#{i}.succ;end\n" '' } h.call(0) eval(str) end require 'benchmark' max = 10000 Benchmark.bm{|x| x.report{ max.times{|i| max.times{|j| } } } x.report{ nloop(max, max){|i, j| } } } ruby 1.9.1p0 (2009-02-02 revision 21960) [i386-mswin32_90] t.rb:12: warning: useless use of a variable in void context user system total real 15.039000 0.000000 15.039000 ( 13.957000) 12.105000 0.031000 12.136000 ( 11.492000) ruby 1.8.7 (2008-12-11 revision 20371) [i386-mswin32_90] t.rb:12: warning: useless use of a variable in void context user system total real 10.671000 0.016000 10.687000 ( 10.642000) t.rb:13:in `nloop': (eval):3:in `nloop': no block given (LocalJumpError) from t.rb:26:in `eval' from t.rb:13:in `nloop' from t.rb:26 from c:/tmp/ruby_1_8/lib/ruby/1.8/benchmark.rb:293:in `measure' from c:/tmp/ruby_1_8/lib/ruby/1.8/benchmark.rb:380:in `report' from t.rb:25 from c:/tmp/ruby_1_8/lib/ruby/1.8/benchmark.rb:177:in `benchmark' from c:/tmp/ruby_1_8/lib/ruby/1.8/benchmark.rb:207:in `bm' from t.rb:18 1. あれー,1.8.7 のほうが times{times{}} が速い なんでー? 2. eval() の中から yield 出来ないんだっけ? Debian etch/amd64 ruby 1.9.2dev (2009-02-26 trunk 22636) [x86_64-linux] user system total real 7.840000 0.000000 7.840000 ( 7.836987) 7.900000 0.000000 7.900000 ( 7.900081) ruby 1.8.5 (2006-08-25) [x86_64-linux] user system total real 30.340000 12.900000 43.240000 ( 43.247637) ../trunk/test.rb:8:in `<<': can't convert nil into String (TypeError) from ../trunk/test.rb:8:in `nloop' from ../trunk/test.rb:8:in `call' from ../trunk/test.rb:8:in `nloop' from ../trunk/test.rb:12:in `call' from ../trunk/test.rb:12:in `nloop' from ../trunk/test.rb:26 from /usr/lib/ruby/1.8/benchmark.rb:293:in `measure' from /usr/lib/ruby/1.8/benchmark.rb:377:in `report' from ../trunk/test.rb:25 from /usr/lib/ruby/1.8/benchmark.rb:177:in `benchmark' from /usr/lib/ruby/1.8/benchmark.rb:207:in `bm' from ../trunk/test.rb:18 3. 1.9 でも times{times{}} のほうが速い−.なんでー? 4. 1.8.7 とバックトレースが違う−. -- // SASADA Koichi at atdot dot net