Reputation: 12224
I'm trying to test that a regex will match a 2-digit number. I get:
11 =~ /^\d{1,2}$/
# => nil
Yet the regex works flawlessly on Rubular. What am I doing wrong?
Upvotes: 2
Views: 84
Reputation: 8978
You are applying regex on number instead of string so convert it to string and try again.
Upvotes: 0
Reputation: 168101
You are calling Kernel#=~
, which always returns nil
.
Rubular does not interpret your input as Ruby code, it interprets is as string literal. That is why it works there.
Upvotes: 3
Reputation: 36101
The problem is that you are testing the regex against a number and not a string. Regexes are intended for matching strings. Simply:
'11' =~ /^\d{1,2}$/
or
11.to_s =~ /^\d{1,2}$/
Upvotes: 8