Issue #13123 has been updated by Shyouhei Urabe.


Tl;dr:  use &.

Longer story:
Generally speaking, there are two major ways of how a null-ish object behaves; whether it should silently ignore methods that makes sense for other classes, or to explicitly raise exceptions for such cases.  An example of former strategy is the nil expression of Objective-C, and Stalltalk's nil is an example of latter.  In late 90s though early 00s, there were discussions which was superior.  I remember that both side have merits.  So it is ultimately a matter of choice.  So far, Ruby preferred to raise early in this context.  I believe Matz intentionally chose the current way.

This has lead people to monkey-patch NilClass before.  Making nil a general-purpose null object is in fact possible that way.  But now that we have the &. operator.  By using it you can explicitly state that you are expecting both nil and (say) Hash, in that specific context.  This is much superior than globally defining method that does nothing.  Fine-grained control over how a nil should behave is made possible this way.  I think current Ruby design is cherry-picking goods of both strategies.  So I think we should encourage &. in general.

Some readings you might find interesting:

- http://wiki.squeak.org/squeak/5962
- http://wiki.c2.com/?NullObject (note how it has both "Null Ls Benign" and "Null Is Hack" sub-pages)
- https://en.wikipedia.org/wiki/Null_Object_pattern

----------------------------------------
Feature #13123: NilClass#dig
https://bugs.ruby-lang.org/issues/13123#change-62464

* Author: Tsuyoshi Sawada
* Status: Open
* Priority: Normal
* Assignee: 
* Target version: 
----------------------------------------
We now have `Hash#dig`. We often have a variable that is either a hash or nil but we are not sure which. In such cases, it would be convenient if we can apply `dig` without conditioning on whether it is a hash or nil.

```ruby
h = {a: 1}
h.dig(:a) # => 1

h = nil
h.dig(:a) # => nil
```



-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>