Feature #13123



Added by sawa (Tsuyoshi Sawada) over 4 years ago. Updated over 2 years ago.

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.

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

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

Updated by shyouhei (Shyouhei Urabe) over 4 years ago

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:

Updated by sawa (Tsuyoshi Sawada) over 2 years ago

I am convinced by shyouhei's comment. Please close this feature request.

Actions #3

Updated by jeremyevans0 (Jeremy Evans) over 2 years ago

  • Status changed from Open to Closed

Also available in: Atom PDF