From: matthew@... Date: 2016-01-20T18:36:39+00:00 Subject: [ruby-core:72991] [Ruby trunk - Feature #11999] MatchData#to_h to get a Hash from named captures Issue #11999 has been updated by Matthew Kerwin. Yui NARUSE wrote: > Yukihiro Matsumoto wrote: > > I don't think `to_h` is appropriate, because `MatchData` is not always able to convert to Hash/Map. > > Is there any name candidate? > > I feel it can always convert to Hash because even if it doesn't use named captures, the numbering is 1-origin. > > ``` > irb(main):001:0> /(a)(b)(c)/.match("abc") > => # > irb(main):002:0> /(a)(b)(c)/.match("abc").to_h > => {1=>"a", 2=>"b", 3=>"c"} > ``` I did some experimenting of my own to this end, and came up with this: https://github.com/phluid61/mug/blob/master/lib/mug/matchdata/hash.rb The only real weirdness arises from the fact that positional captures don't happen at all if there's a named capture group in the Regexp; but given the resulting mutual exclusivity, the code itself becomes pretty straight-forward. ---------------------------------------- Feature #11999: MatchData#to_h to get a Hash from named captures https://bugs.ruby-lang.org/issues/11999#change-56211 * Author: sorah 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(/(?.)(?.)(?.)?/).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: