Project

General

Profile

Actions

Feature #16601

open

Let `nil.to_a` and `nil.to_h` return a fixed instance

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

Status:
Open
Assignee:
-
Target version:
-
[ruby-core:97028]

Description

Now, nil.to_s returns a fixed instance:

nil.to_s.object_id # => 440
nil.to_s.object_id # => 440
nil.to_s.object_id # => 440
...

This is useful when we have some variable foo which may be either nil or a string, and we want to check its emptiness in a condition:

if foo.to_s.empty?; ... end

By this feature, we do not (need to) create a new instance of an empty string each time we check foo, even when it happens to be nil.

There are similar situations with arrays and hashes. We may have variable bar which may be either nil or an array, or baz which may be either nil or a hash, and we want to check their emptiness in conditions as follows:

if bar.to_a.empty?; ... end
if baz.to_h.empty?; ... end

But unlike nil.to_s, the methods nil.to_a and nil.to_h create new instances of empty array or hash each time they are called:

nil.to_a.object_id # => 540
nil.to_a.object_id # => 560
nil.to_a.object_id # => 580
...

nil.to_h.object_id # => 460
nil.to_h.object_id # => 480
nil.to_h.object_id # => 500
...

The fact that this is somewhat inefficient discourages the use of foo.to_a or foo.to_h in such use cases.

I request nil.to_a to nil.to_h to return a fixed empty instance.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0