2

Since ruby 2.3.0, you can call []= method on nil. I don't understand the purpose of this method.

For instance:

nil[1] = 1
# or
nil['foo'] = 'bar'

but [] method does not exist:

nil[1]
# => NoMethodError: undefined method `[]' for nil:NilClass

The ruby 2.3.0 changelog does not mention that changes, although it seems close to the safe navigation operator.

What is the purpose of this operator?

kamaradclimber
  • 2,479
  • 1
  • 26
  • 45
  • Which build of Ruby do you run? What OS do you use? How did you install Ruby 2.3.0? Is it a fresh installation or do you have additional gems installed? – spickermann Apr 27 '16 at 15:58

2 Answers2

0

That method isn't documented in Ruby 2.3.0 and I cannot reproduce this behavior in Ruby 2.3.1 (both examples raise NoMethodError: undefined method '[]=' for nil:NilClass).

Furthermore I reinstalled 2.3.0 and was only partly able to reproduce your examples:

$ rbenv install 2.3.0
Downloading ruby-2.3.0.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.3/ruby-2.3.0.tar.bz2
Installing ruby-2.3.0...
Installed ruby-2.3.0 to /Users/spickermann/.rbenv/versions/2.3.0

$ rbenv shell 2.3.0

$ ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin15]

$ irb
irb   > RUBY_VERSION
irb  => "2.3.0"
irb   > nil[1] = 1
irb  => nil
irb   > nil['foo'] = 'bar'
NoMethodError: undefined method `[]=' for nil:NilClass
  from (irb):3
  from /Users/spickermann/.rbenv/versions/2.3.0/bin/irb:11:in `<main>'

It seems like NilClass#[]= doesn't work properly in Ruby 2.3.0. Since it was completely removed in 2.3.1, I guess that this method or this behavior was added by accident.

Update: Cary Swoveland pointed out in a comment on another question that this behavior was a bug and was fixed in later versions (see: https://bugs.ruby-lang.org/issues/11976).

spickermann
  • 100,941
  • 9
  • 101
  • 131
0

That seems to be actually a bug in 2.3.0 - https://bugs.ruby-lang.org/issues/11976

It does not evaluate the arguments:

nil[undefined_index_variable] = raise "Fooo!" # => nil
Vasfed
  • 18,013
  • 10
  • 47
  • 53