Issue #11999 has been updated by Matthew Kerwin.


Martin Dürst wrote:
> Matthew Kerwin wrote:
> 
> > I think #named_captures is the best name, since that is precisely what it returns (i.e. it never includes numbered captures.)
> 
> Could it make sense to include numbered captures in the hash, too? Just thinking aloud.

I thought so myself, but the regular expression engine currently does numbered captures only if there are no named captures.

> **Note:** A regexp can't use named backreferences and numbered backreferences simultaneously.

-- http://ruby-doc.org/core-2.1.1/Regexp.html#class-Regexp-label-Capturing

I guess this is spec.

----------------------------------------
Feature #11999: MatchData#to_h to get a Hash from named captures
https://bugs.ruby-lang.org/issues/11999#change-56150

* Author: Shota Fukumori
* Status: Open
* Priority: Normal
* Assignee: 
----------------------------------------
~~~
class MatchData
  def to_h
    self.names.map { |n| [n, self[n]] }.to_h
  end
end

p '12'.match(/(?<a>.)(?<b>.)(?<c>.)?/).to_h #=> {"a"=>"1", "b"=>"2", "c"=>nil}
~~~

Sometimes I want to get a Hash from named capture, but currently I have to use #names + #captures. How about adding MatchData#to_h for convenience way?



---Files--------------------------------
11999.diff (2.77 KB)


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

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>