Feature #8396

Allow easier destructuring of MatchData

Added by Gosha Arinich 11 months ago. Updated 11 months ago.

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

Description

=begin

(((I have opened ((<"a PR for this on GH @ rails/rails"|URL:https://github.com/ruby/ruby/pull/300>)) for this but @marcandre closed it and suggested I submit it here. I'll copy my proposal text here.)))

Currently, you can get something out of (({MatchData})) like this:

m = "2apples".match /(\d+)(apple|orange)s?/
count, thing = m[1], m[2]
# or
, count, thing = "2apples".match(/(\d+)(apple|orange)s?/).toa
# or
count, thing = "2apples".match(/(\d+)(apple|orange)s?/).captures
# or, as @marcandre suggested, you can use splat operator
, count, thing = * "2apples".match /(\d+)_(apple|orange)s?/

However, this extra (({#to_a})) or (({#captures})) (or splat) that you have to add makes things slightly more verbose.

With this PR, it would be possible to do the following:

count, thing = "2apples".match /(\d+)(apple|orange)s?/

Which looks a bit cleaner and nicer. So what do you think?

=end

match_data_to_ary.patch Magnifier (827 Bytes) Gosha Arinich, 05/12/2013 06:49 PM

History

#1 Updated by Yukihiro Matsumoto 11 months ago

I like the basic idea, but #to_ary is a method to convert into array implicitly, that means it expect the receiver provides array behavior. MatchObject does not behave like Array.
Maybe we should add another implicit conversion method for right hand side of multiple assignment.

Matz.

#2 Updated by Jeremy Evans 11 months ago

This could be a use case for the @* method proposed in #2013.

#3 Updated by Gosha Arinich 11 months ago

=begin
Yep, the (({*@})) is a nice idea. Would be awesome if it could be used for splat-less destructuring as well. @matz what do you think about this?
=end

#4 Updated by Yui NARUSE 11 months ago

You can use named capture assigning

irb(main):005:0> /(?\d+)(?apple|orange)s?/ =~ "2apples"
=> 0
irb(main):006:0> count
=> "2"
irb(main):007:0> thing
=> "apple"

#5 Updated by Zachary Scott 11 months ago

  • Status changed from Open to Feedback

Also available in: Atom PDF