From: Josh Cheek Date: 2013-04-02T20:03:40+09:00 Subject: Re: Ruby Gotchas presentation slides --f46d0401677d671aba04d95eb08b Content-Type: text/plain; charset=ISO-8859-1 On Sun, Mar 31, 2013 at 1:36 AM, Josh Cheek wrote: > > The example for local var in the block seems too contrived. It's only ever > hit me when I tried to do something like `.each{ |i| sum ||= 0; sum += i }` > in the loop, in which case it always gets set to zero. > > There's also the opposite side of this, which is that a var in a for loop doesn't open a new scope on each invocation, which can be confusing because all iterations are using the same variable. blocks = [] 1.upto(5) { |i| blocks << lambda { i } } blocks.map &:call # => [1, 2, 3, 4, 5] blocks = [] for i in 1..5; blocks << lambda { i } end blocks.map &:call # => [5, 5, 5, 5, 5] Or could cause you to override a variable you meant to shadow var = 100 1.upto(10) { |var| } var # => 100 for var in 1..10; end var # => 10 Might be too nuanced, but if you don't understand the object model, it might be unclear why include doesn't override your instance methods. module A def meth 'A#meth' end end class B def meth 'B#meth' end include A end B.new.meth # => "B#meth" --f46d0401677d671aba04d95eb08b Content-Type: text/html; charset=ISO-8859-1 Content-Transfer-Encoding: quoted-printable
On Sun, Mar 31, 2013 at 1:36 AM, Josh Cheek <josh.chee= k@gmail.com> wrote:

The example for local var in the block seems too contrived. It's o= nly ever hit me when I tried to do something like `.each{ |i| sum ||=3D 0; = sum +=3D i }` in the loop, in which case it always gets set to zero.


There'= ;s also the opposite side of this, which is that a var in a for loop doesn&= #39;t open a new scope on each invocation, which can be confusing because a= ll iterations are using the same variable.

blocks =3D []
1.upto(5) { |i| block= s << lambda { i } }
blocks.map &:call # =3D> [1, 2, = 3, 4, 5]

blocks =3D []
=
for i in 1..5; blocks << lambda { i } end
blocks.map &:= call # =3D> [5, 5, 5, 5, 5]


Or could cause you to override a variable you meant to shadow=

var =3D 100

1= .upto(10) { |var| }
var # =3D> 100

fo= r var in 1..10; end
var # =3D> 10

Might be too nuanced, but if you don't understand the object= model, it might be unclear why include doesn't override your instance = methods.

module A
=A0 d= ef meth
=A0 =A0 'A#meth'
=A0 end
end
class B
=A0 def meth
=A0 =A0 'B#meth= 9;
=A0 end

=A0 include A
e= nd

B.new.meth # =3D> "B#meth"

=
--f46d0401677d671aba04d95eb08b--