In another thread, I encounter this Ruby expression:
str[%r{.*//(.*)}, 1]
What kind of syntax is this? What does the number 1 mean?
Basically, this indexes a string based on a regular expression, and returns the first match group. For example:
str = 'http://example.com'
str[%r{.*//(.*)}, 1]
# => "example.com"
String#slice has this to say:
If a Regexp is supplied, the matching portion of str is returned. If a numeric or name parameter follows the regular expression, that component of the MatchData is returned instead. If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.
You can see the explanation of regex slice in CodeGnome's answer. Here's something about MatchData: str[%r{.*//(.*)}, 1] is equivalent to str.match(%r{.*//(.*)})[1], and they both work in the same way. The [] version is more clear and shorter.
A MatchData acts as an array and/or hash and may be accessed using the normal indexing techniques.
m = /(.)(.)(\d+)(\d)/.match("THX1138.") # m is a MatchData
# and m is #<MatchData "HX1138" 1:"H" 2:"X" 3:"113" 4:"8"> in irb
m[0] # "HX1138"
m[1] # "H"
m[1..2] #["H", "X"]