I got expected result with =~ but not with match. Why does match give the memory reference instead of the actual match data "foo"? And why do the references change in every run of the same statement?
s= "foo"
/(?=foo)foo/ =~ s # => 0
/(?=foo)foo/.match s # => #<MatchData:0x2e6a490>
/(?=foo)foo/.match s # => #<MatchData:0x2e66390>
/(?=foo)foo/.match s # => #<MatchData:0x2e64310>
@theTinMan is mostly correct, the reference is the output of the object’s
to_sorinspectmethod (IRB just calls it, andObject‘s implementation is used via inheritance if it has not been over-riden)The
=~method returns the match position, because that is how it is defined. AMatchDataobject is actually a richer object that has information on the match, such as the offset (the position), any captures, etc. In essence, you can use the returnedMatchDatato access the values that the$~,$1,$2, etc. variables normally hold, with a clearer interface.Docs for
MatchData: http://apidock.com/ruby/MatchData