Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 512
larsch Avatar asked Apr 24 '16 21:04

larsch


People also ask

What is nil Ruby?

nil is a special Ruby data type that means "nothing". It's equivalent to null or None in other programming languages.

How do you check if a variable is nil in Ruby?

That's the easy part. In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).


1 Answers

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
like image 64
Stefan Avatar answered Oct 02 '22 14:10

Stefan