Reputation: 31
I'm a bit confused about answer to the following question from RubyMonk.
Let's find the second character in the string 'RubyMonk Is Pretty Brilliant' preceded by a space, which should be 'P'
'RubyMonk Is Pretty Brilliant'.match(/ ./, 9)
Why would I place a '9' in the argument?
I would really appreciate an explanation.
Upvotes: 2
Views: 127
Reputation: 303136
As mentioned in the comment, the code is 'cheating' by matching a space followed by a character starting after the 9th character. It is—frankly—a terrible example of how to do what it claims to be doing, since you cannot do this generically.
If you really wanted to find the second character that is preceded by a space, and you didn't cheat and look for yourself where it might be, you could do one of the following:
str = 'RubyMonk Is Pretty Brilliant'
Find a space, followed by a non-space, followed by one or more non-space, followed by a space, followed by a character. Capture that character:
str[/ [^ ]+ (.)/,1]
#=> "P"
Find all the characters that are preceded by a space, and then find the second one:
str.scan(/(?<= )./)[1]
#=> "P"
Split on spaces (only keeping the first three chunks, for efficiency), and then find the third match, then find the first character:
str.split(' ',3)[2][0]
#=> "P"
Upvotes: 3
Reputation: 73589
The Monk clearly says
When the second parameter is present, it specifies the position in the string to begin the search.
Upvotes: 3