In Ruby, why does nil[1]=1 evaluate to nil?

后端 未结 1 1256
没有蜡笔的小新
没有蜡笔的小新 2020-12-04 01:39

For example:

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

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



        
相关标签:
1条回答
  • 2020-12-04 02:08

    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
    
    0 讨论(0)
提交回复
热议问题