Project

General

Profile

Actions

Feature #13123

closed

NilClass#dig

Added by sawa (Tsuyoshi Sawada) about 7 years ago. Updated almost 5 years ago.

Status:
Closed
Assignee:
-
Target version:
-
[ruby-core:79052]

Description

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) about 7 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) almost 5 years ago

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

Actions #3

Updated by jeremyevans0 (Jeremy Evans) almost 5 years ago

  • Status changed from Open to Closed
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0