Feature #13645
openSyntactic sugar for indexing when using the safe navigation operator
Description
Proposal¶
While it works and makes sense, this is a bit cumbersome:
hash&.[](:key)
Ideally, we could use something like:
hash&.[:key]
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?
Updated by sawa (Tsuyoshi Sawada) over 7 years ago
Duplicate of https://bugs.ruby-lang.org/issues/11813
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.