Tbpgr Blog

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

Ruby | MatchData | captures

概要

MatchData#captures(n) -> Fixnum | nil

詳細

$1, $2, ... を格納した配列を返します。
MatchData#to_a と異なり $& を要素に含みません。
グループにマッチした部分文字列がなければ対応する要素は nil になります。

サンプルコード
require 'tbpgr_utils'

"hogehigehage" =~ /(h\wge)(h\wge)(h\wge)/

bulk_puts_eval binding, <<-EOS
$~.to_a
$~.captures
EOS

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

$~.to_a     # => ["hogehigehage", "hoge", "hige", "hage"]
$~.captures # => ["hoge", "hige", "hage"]