tags:

views:

88

answers:

1
m = /(.)(.)(\d+)(\d)/.match("THX1138.")

puts m[0]

c = m.captures #=> HX1138

puts c[0] #=> H
puts  m.begin(0)   #=> 1

puts c[1] #=> X
puts  m.begin(1)   #=> 1

puts c[2] #=> 113
puts  m.begin(2)   #=> 2

I was expecting m.begin(1) to return 2 since X is two elements after the beginning of string.

I am reading the book well grounded rubyist which says

To get the information for capture n, you provide n as the argument to begin and/or end.

Similarly I was expecing m.begin(2) to rerturn 3.

+8  A: 

Read carefully:

Returns the offset of the start of the nth element of the match array in the string.

So the match array is actually [HX1138,H,X,113,8]

SO

   m.begin(0) => offset of HX1138 => 1 in "THX1138"
   m.begin(1) => offset of H => 1      in "THX1138"
   m.begin(2) => offset of X => 2      in "THX1138"
ennuikiller
I edited the original question and added what the well grounded rubyist book says. Looks like I misprint in the book. Thanks for the answer.
Roger