Project

General

Profile

Actions

Feature #13645

open

Syntactic sugar for indexing when using the safe navigation operator

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

Status:
Open
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 1 (0 open1 closed)

Is duplicate of Ruby master - Feature #11813: Extend safe navigation operator for [] and []= with syntax sugarRejectedmatz (Yukihiro Matsumoto)Actions

Updated by shevegen (Robert A. Heiler) over 7 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&. 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?

Actions #3

Updated by znz (Kazuhiro NISHIYAMA) over 7 years ago

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

Updated by osyo (manga osyo) over 5 years 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.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0