7

What's the difference between string.match(regex) and regex.match(string) in Ruby? What's the justification for having both those constructs in the language?

2 Answers 2

4

Aside from hanging off of different objects (which sometimes makes it more convenient to call one instead of the other), they are the same. The justification is that they are both useful and one is sometimes more convenient than the other.

Sign up to request clarification or add additional context in comments.

4 Comments

I don't really like that justification (probably there isn't one better than "they're there, so live with it"). They're both useful because they both have the same use. I can be argued that the existence of one makes the other useless.
Except that they don't have the same use. They just have very similar uses. In any event, I'm not convinced that they require justification. If you really want a Ruby language feature that needs justification (and lacks it), go for for ... in ... loops.
So they are not the same? Can you improve your answer to reflect that?
Not being a ruby programmer, I find that fantastic - because I use regexes in different languages and every other time I get it in the wrong order - would be good if one could rely on that the order does not matter in other languages too.
1

I thnk that, intuitively, match, or the related method =~, expresses some kind of equality, as reflected in the fact that =~ includes the equality = and the equivalence ~ relations (not in ruby but in mathematics). But it is not totally an equivalence relation, and among the three axioms of equality (reflexivity, commutativity, transitivity), particularly commutativity seems reasonable to be maintaind in this relation; it is natural for a programmer to expect that string.match(regex) or string =~ regex would mean the same thing as regex.match(string) or regex =~ string. I myself, would have problem remembering if either is defined and not the other. In fact, some people feel it strange that the method ===, which also reminds us of some kind of equality, is not commutative, and have raised questions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.