The statement from the documentation ( http://ruby-doc.org/core/classes/String.html#M001185 ), here are the answers to your two questions: "why is the return value" one t-three '"and" what does {$ 1 [0, 1]}? "
What does {$ 1 [0, 1]} mean? The String # sub method can take either two arguments, or one argument, and a block. The latter is the form used here, and it is just like the Integer.times method, which takes a block:
5.times { puts "hello!" }
So this explains the closing braces.
$ 1 is a substring corresponding to the first regular expression capture group, as described here . [0, 1] is the string method "[]", which returns a substring based on the values โโof the array โ here, the first character.
Combine, {$ 1 [0, 1]} is the block that returns the first character in $ 1, where $ 1 is the substring that was matched by the capture group when the last expression was used to match the string.
Why is the return value one t three? The String # sub ('substitute') method, unlike its brother String # gsub ('global substitute'), replaces the first part of the string corresponding to the regular expression, with its replacement. Therefore, this method will replace the first subscript match "(t \ w *)" with the value of the block described above, i.e. With its first character. Since โtwoโ is the first subscript match (t \ w *) (a 't', followed by any number of letters), it is replaced by its first character, 't'.
source share