Emiliano Poggi
Emiliano Poggi

Reputation: 24816

ruby rspec and strings comparison

I'm not a ruby expert and may be this will seem a silly question...but I'm too courious about an oddity (I think) I've found in RSpec matcher called match.

You know match takes in input a string or a regex. Example:

"test".should match "test" #=> will pass
"test".should match /test/ #=> will pass

The strange begins when you insert special regex characters in the input string:

"*test*".should match "*test*" #=> will fail throwing a regex exception

This means (I thought) that input strings are interpreted as regex, then I should escape special regex characters to make it works:

"*test*".should match "\*test\*" #=> will fail with same exception
"*test*".should match /\*test\*/ #=> will pass

From this basic test, I understand that match treats input strings as regular expressions but it does not allow you to escape special regex characters.

Am I true? Is not this a singular behavior? I mean, it's a string or a regex!


EDIT AFTER ANSWER:

Following DigitalRoss (right) answer the following tests passed:

"*test*".should match "\\*test\\*" #=> pass
"*test*".should match '\*test\*' #=> pass
"*test*".should match /\*test\*/ #=> pass

Upvotes: 16

Views: 18554

Answers (1)

DigitalRoss
DigitalRoss

Reputation: 146053

What you are seeing is the different interpretation of backslash-escaped characters in String vs Regexp. In a soft (") quoted string, \* becomes a *, but /\*/ is really a backslash followed by a star.

If you use hard quotes (') for the String objects or double the backslash characters (only for the Strings, though) then your tests should produce the same results.

Upvotes: 13

Related Questions