Project

General

Profile

Actions

Feature #13314

open

dig=

Feature #13314: dig=

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

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

Description

We have Hash#dig, and when we want to assign a key-value at a deep level, it is tempting to do:

hash.dig(:key1, :key2, :key3, :key4) = "value

when we actually needed to do:

hash.dig(:key1, :key2, :key3)&.[]=(:key4, "value")

I propose a method Hash#dig=, which should be equivalent to the following:

class Hash
  def dig=(*keys, final_key, value)
    dig(*keys)&.[](final_key, value)
  end
end

Updated by sawa (Tsuyoshi Sawada) over 8 years ago Actions #1 [ruby-core:80151]

Was this syntactically not allowed? If so, sorry.

Updated by nobu (Nobuyoshi Nakada) over 8 years ago Actions #2 [ruby-core:80152]

Assignment to method call has been a challenge in the last couple of years, but not possible yet,

Updated by nobu (Nobuyoshi Nakada) over 8 years ago Actions #3

  • Description updated (diff)

Updated by Mikr (Mikhail Krainik) over 8 years ago Actions #4 [ruby-core:80155]

you can do that, as example

a = {key1: { key2: { key3: { key4: '4' }}}}; 
a.dig(:key1, :key2, :key3)[:key4] = 4
=> {:key1=>{:key2=>{:key3=>{:key4=>4}}}}
Actions

Also available in: PDF Atom