Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
412 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...