9

For example:

nil[1]     #=> NoMethodError
nil[1]=1   #=> nil

It's not just syntax, as it happens with variables too:

a = nil
a[1]       #=> NoMethodError
a[1]=1     #=> nil

Oddly:

nil.method(:[]=)   #=> NameError
[].method(:[]=)    #=> #<Method...>

Ruby 2.3.0p0

AndreDurao
  • 5,600
  • 7
  • 41
  • 61
larsch
  • 961
  • 8
  • 17
  • Can't reproduce on Ruby 2.2.4. Maybe a new feature or a bug in your version? – Silvio Mayolo Apr 24 '16 at 21:39
  • Weird... Maybe it's a bug. – Juanjo Salvador Apr 24 '16 at 21:42
  • 1
    I can only reproduce this in Ruby 2.3.0 and I'm going to presume it's a bug. It might be worth checking the [bug tracker for this issue](https://bugs.ruby-lang.org). – tadman Apr 24 '16 at 21:48
  • Probably it is fixed already. Cannot be reproduced on ruby 2.3.0p71 (2016-03-30 revision 54426). – sawa Apr 24 '16 at 21:59
  • 6
    I believe the fix was reported [here](https://bugs.ruby-lang.org/issues/11976) ("unexpected safe call"). larsch, how did you happen to stumble onto that? Everyone, raises your glasses! It's not everyday that a suspected bug turns out to actually be a bug. – Cary Swoveland Apr 24 '16 at 22:46
  • This is why we avoid the *latest* version – prusswan Apr 25 '16 at 04:25
  • I simple had an instance variable `@idx = Hash.new` that I was trying to use as `@index[key] = value`. The unittest was failing in strange ways because the assignment didn't fail on the `nil` value. – larsch Apr 26 '16 at 07:37
  • @CarySwoveland Do you want to post that info as an answer so I can mark [this question](http://stackoverflow.com/questions/36894267/what-is-the-purpose-of-method-on-nil) as a duplicate? – Jordan Running Apr 27 '16 at 15:58
  • Thanks, @Jordan, but I'd prefer to leave it as a comment. – Cary Swoveland Apr 27 '16 at 16:15

1 Answers1

1

Some random findings: [only in Ruby 2.3.0p0]

The method doesn't seem to exist:

nil.method(:[]=)      #=> NameError: undefined method `[]='
nil.respond_to?(:[]=) #=> false

And you can't invoke it using send:

nil.send(:[]=)        #=> NoMethodError: undefined method `[]='

Ruby evaluates neither the right hand side, nor the argument, i.e.

nil[foo]=bar

doesn't raise a NameError, although foo and bar are undefined.

The expression seems to be equivalent to nil:

$ ruby --dump=insns -e 'nil[foo]=bar'
== disasm: #<ISeq:<main>@-e>============================================
0000 trace            1                                               (   1)
0002 putnil
0003 leave

$ ruby --dump=insns -e 'nil'
== disasm: #<ISeq:<main>@-e>============================================
0000 trace            1                                               (   1)
0002 putnil
0003 leave
Stefan
  • 109,145
  • 14
  • 143
  • 218