Skip to content

1.6.0: Pattern matching RE2::MatchData

Compare
Choose a tag to compare
@mudge mudge released this 22 Oct 07:38
· 238 commits to main since this release
8bb59cf

In order to support pattern matching in recent versions of Ruby, implement RE2::MatchData#deconstruct and RE2::MatchData#deconstruct_keys. This allows matches to be matched with both array and hash patterns, e.g.

case RE2('(\w+) (\d+)').match("Alice 42")
in [name, age]
  puts "My name is #{name} and I am #{age} years old"
else
  puts "No match!"
end
# My name is Alice and I am 42 years old

case RE2('(?P<name>\w+) (?P<age>\d+)').match("Alice 42")
in {name:, age:}
  puts "My name is #{name} and I am #{age} years old"
else
  puts "No match!"
end
# My name is Alice and I am 42 years old

This is inspired by ruby/ruby#6216. Thanks to @tomstuart for drawing my attention to it.