Issue #8396 has been updated by naruse (Yui NARUSE).


You can use named capture assigning

irb(main):005:0> /(?<count>\d+)_(?<thing>apple|orange)s?/ =~ "2_apples"
=> 0
irb(main):006:0> count
=> "2"
irb(main):007:0> thing
=> "apple"
----------------------------------------
Feature #8396: Allow easier destructuring of MatchData
https://bugs.ruby-lang.org/issues/8396#change-39299

Author: goshakkk (Gosha Arinich)
Status: Open
Priority: Normal
Assignee: 
Category: 
Target version: 


=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 = "2_apples".match /(\d+)_(apple|orange)s?/
 count, thing = m[1], m[2]
 # or
 _, count, thing = "2_apples".match(/(\d+)_(apple|orange)s?/).to_a
 # or
 count, thing = "2_apples".match(/(\d+)_(apple|orange)s?/).captures
 # or, as @marcandre suggested, you can use splat operator
 _, count, thing = * "2_apples".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 = "2_apples".match /(\d+)_(apple|orange)s?/

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

=end


-- 
http://bugs.ruby-lang.org/