Project

General

Profile

Feature #14444

MatchData: alias for #[]

Added by zverok (Victor Shepelev) over 2 years ago. Updated over 1 year ago.

Status:
Feedback
Priority:
Normal
Assignee:
-
Target version:
-
[ruby-core:85389]

Description

After introduction of safe navigation operator and other latest features, it could be pretty idiomatic to do this:

next_page = response.dig('meta', 'pagination', 'next')&.match(/&page=(\d+)/)&.[](1)

The ugly thing here is, obviously, &.[](1). When dealing with other classes we can use dig(one_key) or at(index) for arrays, but for MatchData there are no good synonym/alias.

Two options come to mind:

  • &.capture(1) — singular from "captures"
  • &.at(1) — like it is in Array, from which MatchData already borrows values_at

Yes, several &. in a row could be said a code smell and example may feel a bit extreme.

But for simple matches, the principle stays the same: "match something and extract if matched" otherwise should be written in much less readable code like this:

if url =~ /&page=(\d+)/
  next_page = Regexp.last_match[1]
end
# or
if (m = url.match(/&page=(\d+)/))
  next_page = m[1]
end

# this seems the most reasonable syntax anyways:
next_page = url.match(/&page=(\d+)/)&.at(1)

Also available in: Atom PDF