Feature #8396


Allow easier destructuring of MatchData

Added by goshakkk (Gosha Arinich) over 8 years ago. Updated over 8 years ago.

Target version:



(((I have opened ((<"a PR for this on GH @ rails/rails"|URL:>)) for this but marcandre (Marc-Andre Lafortune) 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 = "2_apples".match /(\d+)(apple|orange)s?/
count, thing = m[1], m[2]
# or
_, count, thing = "2_apples".match(/(\d+)
# or
count, thing = "2_apples".match(/(\d+)(apple|orange)s?/).captures
# or, as marcandre (Marc-Andre Lafortune) suggested, you can use splat operator
_, count, thing = * "2_apples".match /(\d+)

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 = "2_apples".match /(\d+)_(apple|orange)s?/

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



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

Updated by matz (Yukihiro Matsumoto) over 8 years 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.


Updated by jeremyevans0 (Jeremy Evans) over 8 years ago

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

Actions #3

Updated by goshakkk (Gosha Arinich) over 8 years ago

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

Updated by naruse (Yui NARUSE) over 8 years ago

You can use named capture assigning

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

Updated by zzak (Zachary Scott) over 8 years ago

  • Status changed from Open to Feedback

Also available in: Atom PDF