[LRUG] Ruby question for a change! Why does this happen...

Evgeny Shadchnev evgeny.shadchnev at gmail.com
Tue Jul 1 02:16:38 PDT 2014


When you say foo += [], this means foo = foo + []. The first thing that
Ruby sees is foo on the left hand side. Since it's an assignment, it
implicitly creates a new local variable foo that's nil by default. When it
comes to evaluating the right hand side, foo is a reference to this local
variable, not your method.

I'm not 100% correct that this is exactly what's going on, so please
correct me if I'm wrong.

Best,
Evgeny


On Tue, Jul 1, 2014 at 10:12 AM, Kenneth Lee <kenfodder at gmail.com> wrote:

> Doing some lazy instantiation and come across this oddity, maybe I'm just
> being dense.
>
> $ irb
>
> irb(main):001:0> def foo
>
> irb(main):002:1>   @bar ||= []
>
> irb(main):003:1> end
>
> => :foo
>
> irb(main):004:0> foo
>
> => []
>
> irb(main):005:0> foo += []
>
> NoMethodError: undefined method `+' for nil:NilClass
>
> from (irb):5
>
> from /Users/ken/.rbenv/versions/2.1.1/bin/irb:11:in `<main>'
>
> irb(main):006:0> foo
>
> => nil
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.lrug.org/pipermail/chat-lrug.org/attachments/20140701/2208f6b2/attachment.html>


More information about the Chat mailing list