RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

What is wrong with this extremely simple regex?

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

Answers (3)

Saleem
Saleem

Reputation: 8978

You are applying regex on number instead of string so convert it to string and try again.

Upvotes: 0

sawa
sawa

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

ndnenkov
ndnenkov

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

Related Questions