I'm trying to solve problem #6 from the Ruby Quiz book. This problem says I have to create a new method called build()
for Regex class in which, passing integers or ranges, it has to generate a regex to detect the allowed numbers.
For example:
lucky = Regexp.build(3, 7)
"7" =~ lucky # => true
"13" =~ lucky # => false
"3" =~ lucky # => true
month = Regexp.build(1..12)
"0" =~ month # => false
"1" =~ month # => true
"12" =~ month # => true
I developed a buggy version, but it doesn't work as expected. My problem is to generate the correct regex. All the patterns I tried in Rubular don't take what they should. For example, for Regexp.build(1, 3, 5)
I got a pattern which looks like this one:
/^1|3|5$/
This works and it matches 1
, 3
and 5
. But it also matches 15
or 13
.
What's the best way to get the numbers to not combine between them?
---- EDIT
Using groups, now it seems to work properly. Anyway, is there any way for getting regexp that represents a range? For example, keeping the previous example:
lucky = Regexp.build(1..12)
"7" =~ lucky # => true
"13" =~ lucky # => false
"0" =~ lucky # => false
"5" =~ lucky # => true
The regexp generated by Regexp.build would have to match all the values between 1 and 12, but no more. I have been searching around the web and i've seen it's complicated to generate this kind of regex programmatically. Is there any concrete or predefined method for this task?
http://utilitymill.com has a recursive function to accomplish that, but i consider it kinda complicated.