Reputation: 26932
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?
Upvotes: 7
Views: 374
Reputation: 168071
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.
Upvotes: 1
Reputation: 15605
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.
Upvotes: 4