From: "zverok (Victor Shepelev) via ruby-core" Date: 2023-11-09T14:53:33+00:00 Subject: [ruby-core:115323] [Ruby master Feature#14548] Allow some_array&.[1] to be a valid syntax Issue #14548 has been updated by zverok (Victor Shepelev). > What about using `dig` Actually, many codebases are already using `dig` in those cases (and it is _clearer_ without redefinition on `nil`, telling the reader "we are aware there might be `nil` here"): ```ruby array_or_nil&.dig(index) ``` ...but using the proposed solution is shorter and cleaner. > There is also nothing wrong with `array_or_nil && array_or_nil[index]`. ...until it is part of the message chain: ```ruby # bad calculate_some_value(with, some, arguments) && calculate_some_value(with, some, arguments)[index] # wordy, requires inventing new names: intermediate = calculate_some_value(with, some, arguments) intermediate && intermediate[index] ``` Though, even if there is already a variable, `foo && foo[bar]` is already non-DRY and impends reading. > IMO these `?.[` look too cryptic. I honestly don't see how it is more cryptic than `&.foo(`. For the codebases that use `&.` where appropriate, an attempt to write `foo&.[bar]` is what less experienced programmers always try to do, and "why it doesn't work" is more cryptic than if it would. Those are somewhat more confusing, too: ```ruby # I tried to use foo&.[bar], it failed, I know [] is a method and I write this: foo&.[](bar) # I find the above ugly, and I switch to dig: foo&.dig(bar) ``` ...but it is kind of non-standar to use `dig` with one argument, and needs to be remembered as a separate idiom. ---------------------------------------- Feature #14548: Allow some_array&.[1] to be a valid syntax https://bugs.ruby-lang.org/issues/14548#change-105243 * Author: rosenfeld (Rodrigo Rosenfeld Rosas) * Status: Open * Priority: Normal * Assignee: matz (Yukihiro Matsumoto) ---------------------------------------- Currently, Ruby allows accessing an array's index while testing whether the array is not nil with this syntax: `my_array&.[](1)`. I've always found this awkward but didn't mind about suggesting anything to improve this. I was just reading about how JavaScript is probably going to support myArray?.[1] and found that it read good enough for me. So I'd like to propose about the same syntax, replacing ?. with the Ruby equivalent &. instead. How does that look like to you? -- https://bugs.ruby-lang.org/ ______________________________________________ ruby-core mailing list -- ruby-core@ml.ruby-lang.org To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org ruby-core info -- https://ml.ruby-lang.org/mailman3/postorius/lists/ruby-core.ml.ruby-lang.org/