Tbpgr Blog

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

Ruby | MatchData | offset

概要

MatchData#offset

詳細

n 番目の部分文字列のオフセットの配列 [start, end] を返 します。

[ MatchData#.begin(n), MatchData#.end(n) ]

と同じ。

サンプルコード
require 'tbpgr_utils'

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

(1..3).each do |i|
  bulk_puts_eval binding, <<-EOS
$~.begin(i)
$~.end(i)
$~.offset(i)
  EOS
end

__END__
下記はTbpgrUtils gemの機能
bulk_puts_eval

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

出力

$~.begin(i)  # => 0
$~.end(i)    # => 4
$~.offset(i) # => [0, 4]
$~.begin(i)  # => 4
$~.end(i)    # => 8
$~.offset(i) # => [4, 8]
$~.begin(i)  # => 8
$~.end(i)    # => 12
$~.offset(i) # => [8, 12]