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
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.

- 15,437
- 1
- 45
- 55
-
2I 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. – R. Martinho Fernandes Apr 09 '11 at 20:45
-
1Except 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. – Rein Henrichs Apr 09 '11 at 20:51
-
2So they are not the same? Can you improve your answer to reflect that? – R. Martinho Fernandes Apr 09 '11 at 21:03
-
1Not 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. – Ingo Apr 10 '11 at 00:47
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.