Project

General

Profile

Feature #13645

Syntactic sugar for indexing when using the safe navigation operator

Added by ndn (Nikola Nenkov) over 2 years ago. Updated 7 months ago.

Status:
Open
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:81629]

Description

Proposal

While it works and makes sense, this is a bit cumbersome:

hash&.[](:key)

Ideally, we could use something like:

hash&.[:key]

Related issues

Is duplicate of Ruby master - Feature #11813: Extend safe navigation operator for [] and []= with syntax sugarRejectedActions

History

Updated by shevegen (Robert A. Heiler) over 2 years ago

Is this valid syntax? I ask specifically because of the '.' character there. I am not
a big fan of the & anyway though, so I am biased. I am just wondering in context of
syntax such as:

hash[:key]
hash&[:key]
hash&.[:key]

Actually I only consider the first elegant, the rest ugly. But I see your point
in regards to hash&.[](:key) versus hash&.[:key] - if the former already works
as-is, then it may make sense to allow for the latter. What I thought was that
the '.' is explicit for the method call; I guess the last example:

hash&.[:key]

Would then be equivalent to:

hash&.[(:key)]

right?

#3

Updated by znz (Kazuhiro NISHIYAMA) over 2 years ago

  • Is duplicate of Feature #11813: Extend safe navigation operator for [] and []= with syntax sugar added

Updated by osyo (manga osyo) 7 months ago

hi. I would like to use hash&.[key] (or hash&[key] ) in following cases as below.

class X
  def initialize
    @hash = { a: 1, b: 2, c: 3 }
  end

  def [](key)
    @hash[key]
  end
end

def get(key)
  x = Symbol === key && X.new || nil
  # I want to use x&.[key] (or x&[key])
  x&.[](key)
end

p get(:a)     #=> 1
p get("b")    # => nil

Matz writes

Use #dig for referencing the value.
For updating, show us use cases.
https://bugs.ruby-lang.org/issues/11813#note-6

However, YOU can not use x&.dig(key) for a class that Mr. Matz has previously proposed for which #dig is not defined.

Also available in: Atom PDF