From: hanmac@...
Date: 2016-01-19T08:11:03+00:00
Subject: [ruby-core:72929] [Ruby trunk - Feature #11999] MatchData#to_h to get a Hash from named captures

Issue #11999 has been updated by Hans Mackowiak.


also interesting if you have a with | combined regexp where both of them does have a named capture:

```ruby
reg = /(?<a>b)|(?<a>x)/ # => /(?<a>b)|(?<a>x)/ 
reg.match("abc") # => #<MatchData "b" a:"b" a:nil>
reg.match("abc").captures #=> ["b", nil]
reg.match("abc")[:a] # => "b" 
reg.match("xyz") # => #<MatchData "x" a:nil a:"x"> 
reg.match("xyz").captures #=> [nil, "x"]
reg.match("xyz")[:a] # => "x"
```

(also notice that in the inspect of MatchData the capture :a is shown twice.)
such things does need to be remembered when creating a new function for MatchData

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

* 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>