🚀
[Feature #21190] `MatchData#deconstruct` を追加する提案
[Feature #21190] Proposal for the Deconstruct Method in the MatchData Class
-
MatchData
でパターンマッチが利用できるようにMatchData#deconstruct
を追加する提案 - 以下のように
MatchData#deconstruct
がMatchData#to_a
を返すようなイメージ
class MatchData
def deconstruct
self.to_a
end
end
result = /(\d{2})(\d{2})(\d{9})/.match("5586987654321")
result in [_ , country_code, area_code, number] # 先頭は "5586987654321" になる
puts country_code # => "55"
puts area_code # => "86"
puts number # => "987654321"
- これなんですが以下のように名前付きキャプチャを利用することがコメントで提案されていますね
/(?<country_code>\d{2})(?<area_code>\d{2})(?<number>\d{9})/ =~ "5586987654321"
country_code # => "55"
area_code # => "86"
number # => "987654321"
- また
MatchData#deconstruct
は既に定義されておりMatchData#captures
を返すようになっているので以下のように利用することもできます-
MatchData#captures
は#to_a
から先頭を除いた配列を返す
-
result = /(\d{2})(\d{2})(\d{9})/.match("5586987654321")
p result.deconstruct #=> ["55", "86", "987654321"]
p (result in [country_code, area_code, number]) #=> true
p [country_code, area_code, number] #=> ["55", "86", "987654321"]
Discussion