In the book Eloquent Ruby (page 21, first edition, sixth printing), the author (Russ Olsen) advocates using the each
method instead of
How can I show the Ruby for loop is in fact implemented using the each method?
Look at the bytecode.
ruby --dump insns -e 'for n in 1..10; puts n; end'
Which prints
== disasm: @>==========
== catch table
| catch type: break st: 0002 ed: 0006 sp: 0000 cont: 0006
|------------------------------------------------------------------------
local table (size: 2, argc: 0 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] n
0000 trace 1 ( 1)
0002 putobject 1..0
0004 send >
0006 leave
== disasm: @>=
== catch table
| catch type: redo st: 0006 ed: 0013 sp: 0000 cont: 0006
| catch type: next st: 0006 ed: 0013 sp: 0000 cont: 0013
|------------------------------------------------------------------------
local table (size: 2, argc: 1 [opts: 0, rest: -1, post: 0, block: -1, kw: -1@-1, kwrest: -1])
[ 2] ?
0000 getlocal_OP__WC__0 2 ( 1)
0002 setlocal_OP__WC__1 2
0004 trace 256
0006 trace 1
0008 putself
0009 getlocal_OP__WC__1 2
0011 opt_send_without_block
0013 trace 512
0015 leave
As you can see it calls each
with a block on the first 0004
line.