Blankman
Blankman

Reputation: 267320

What is this regex doing? match = /^plus_([0-9]+)$/.match(m.to_s)

What is this RUBY regex doing:

match = /^plus_([0-9]+)$/.match(m.to_s)

It seems to be matching 'plus_' and then a number.

But what is the .match(m.to_s) part doing? is it chaining to itself? I don't understand.

Sorry its Ruby.

Upvotes: 0

Views: 170

Answers (3)

Kevin Anderson
Kevin Anderson

Reputation: 7010

I've never looked at ruby, but based on what others have said here, this seems to be calling the "match" method of the regex that was just defined, against the string "m".

So the regex itself becomes an "object", to which the method "match" is called, and the argument is the result of (m.to_s), which is just a string. The result of the "match()" method is then returned into a variable named "match".

I think the fact that the method call is the same name as the return variable is what's making this seem weird.

Now this could be 100% wrong, as I've NEVER looked at ruby, but based on what others have said, this is what it looks like.

Upvotes: 0

Max
Max

Reputation: 22385

Haha, nice edit! I thought it was Ruby to begin with - my answer still holds.

You are correct about what the regex matches. However, .match() is the method used to match the regex against strings. It returns a MatchData object which you can then use to find out information about the match.

So /^plus_([0-9]+)$/ creates a regex object, .match(m.to_s) matches it against m as a string, and the resulting MatchData is stored in match.

See the Regexp documenation.

Upvotes: 1

user395760
user395760

Reputation:

Calling .match(s) on a regex runs the regex against s and returns a MatchData object. m.to_s simply means "call the to_s method of m" (i.e. convert it to a string).

Upvotes: 2

Related Questions