2

I've just noticed a very puzzling change in behaviour between Ruby 2.2.4 and Ruby 2.3.0: trying to use [] on nil in an assignment does not raise a NoMethodError anymore.

Ruby 2.2.4:

box:~ jfoeh$ irb
2.2.4 :001 > a = nil
 => nil 
2.2.4 :002 > a[:b] = 1
NoMethodError: undefined method `[]=' for nil:NilClass
    from (irb):2
from /Users/jfoeh/.rvm/rubies/ruby-2.2.4/bin/irb:11:in `<main>'

In contrast Ruby 2.3.0:

box:~ jfoeh$ irb
2.3.0 :001 > a = nil
 => nil 
2.3.0 :002 > a[:b] = 1
 => nil 

Is that behaviour expected, or is this a regression of sorts?

We originally noticed this when we found such an assignment seemingly swallowing exceptions in 2.3:

2.3.0 :001 > require 'date'
 => true 
2.3.0 :002 > a = nil
 => nil 
2.3.0 :003 > a[:b] = Date.parse(nil)
 => nil

whereas Ruby 2.2 would execute the right-hand side first and raise a TypeError as one would expect.

janfoeh
  • 10,243
  • 2
  • 31
  • 56
  • Interesting... I can't find anything in the documentation of ruby 2.3 NilClass. This behavior of nil doesn't feel right, I agree with you. Have you tried submitting an issue to https://github.com/ruby/ruby ? – Caillou Jun 28 '16 at 08:31
  • @Caillou I haven't; the project does not seem to have the issue tracker enabled on GH? – janfoeh Jun 28 '16 at 08:37
  • I tried 2.3.0 and 2.3.1 and it looks correct in 2.3.1. – Ursus Jun 28 '16 at 08:44
  • @Ursus interesting, thanks! That points towards 'bug'… – janfoeh Jun 28 '16 at 08:45
  • @TomLord I've searched high and low and came up empty. If you happen to have an answered question handy, feel free to mark as duplicate. – janfoeh Jun 28 '16 at 08:56

1 Answers1

2

This was a bug introduced in ruby version 2.3.0. It has since been fixed, as of version 2.3.1.

Here is the original issue that was raised, on ruby-lang.org, and here is the commit which resolves the issue.

Tom Lord
  • 27,404
  • 4
  • 50
  • 77