Project

General

Profile

Actions

Feature #18334

open

ENV#to_h returns a new Hash object but Hash#to_h does not, which can cause inconsistencies

Added by postmodern (Hal Brodigan) about 3 years ago. Updated about 3 years ago.

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

Description

I noticed that in ruby-3.1.0-preview1 ENV#dup was removed in favor of ENV#to_h. However, methods that accept either ENV or a Hash object will not behave the same, since ENV#to_h returns a new Hash object but Hash#to_h returns the same Hash instance.

ENV.to_h.object_id
# => 14700
ENV.to_h.object_id
# => 14760
hash = {"FOO" => "bar"}
hash.to_h.object_id
# => 14820
hash.to_h.object_id
# => 14820

I propose that the ENV#dup method be re-added as self.to_h.dup.

Updated by Eregon (Benoit Daloze) about 3 years ago

I think it would be confusing if ENV#dup returns a Hash and not a ENV, as that would be inconsistent with all other #dup.

to_SHORT never guarantees to return a copy, so if you don't know the receiver and want to mutate the result, you should probably use obj.to_h.dup, which already works fine.

Updated by postmodern (Hal Brodigan) about 3 years ago

With the current implementation of ENV#to_h, ENV.to_h.dup would create two new Hashes instead of one. hash.to_h.dup would correctly create only one new Hash.

Actions #3

Updated by jeremyevans0 (Jeremy Evans) about 3 years ago

  • Tracker changed from Bug to Feature
  • ruby -v deleted (ruby 3.1.0dev (2021-11-13T20:48:57Z master fc456adc6a) [x86_64-linux])
  • Backport deleted (2.6: UNKNOWN, 2.7: UNKNOWN, 3.0: UNKNOWN)
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0