Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | MatchData | names

概要

MatchData#names

詳細

名前付きキャプチャの名前を文字列配列で返します。

サンプルコード
require 'tbpgr_utils'

"hogehigehage" =~ /(?<ho>ho.*)(?<hi>hi.*)(?<ha>ha.*)/

bulk_puts_eval binding, <<-EOS
$~
$~[:ho]
$~[:hi]
$~[:ha]
$~.names
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

https://rubygems.org/gems/tbpgr_utils
https://github.com/tbpgr/tbpgr_utils

出力

$~       # =>                   #<MatchData "hogehigehage" ho:"hoge" hi:"hige" ha:"hage">
$~[:ho]  # => "hoge"
$~[:hi]  # => "hige"
$~[:ha]  # => "hage"
$~.names # => ["ho", "hi", "ha"]