views:

35

answers:

2

Im setting up a simple checker program thing. For now, its extremely simple and is jsut checking integers. I dont think the regular expressions are wrong, but I am new to ruby.

testing out the auto-regex

def createRegexClosure(re)
        reg = Regexp.new(re)
        return lambda { |t|
            return reg.match(t)
        }
end

predefinedRegex = {
        '+int' => '/[1-9][0-9]*/',
        'int' => '/-?[0-9]+/',
        '-int' => '/-[0-9]+/'
}

positiveInt = createRegexClosure(predefinedRegex['+int'])
normalInt = createRegexClosure(predefinedRegex['int'])
negativeInt = createRegexClosure(predefinedRegex['-int'])

puts positiveInt.call('5932423') ? 'good' : 'bad'
puts normalInt.call('0') ? 'good' : 'bad'
puts normalInt.call('-2121') ? 'good' : 'bad'
puts negativeInt.call('-32332') ? 'good' : 'bad'

and it prints out bad 4 times in a row. This is not possible.

+3  A: 

I believe you need to remove the / characters from predefinedRegex. The parameter to Regexp.new is expected to be a pattern from which the regular expression is created.

predefinedRegex = {
        '+int' => '[1-9][0-9]*',
        'int' => '-?[0-9]+',
        '-int' => '-[0-9]+'
}

In addition, depending on what your goal is, you might want anchor characters (^ and $) in the expressions.

Mark Wilkins
+2  A: 

either

predefinedRegex = {
    '+int' => '[1-9][0-9]*',
    'int' => '-?[0-9]+',
    '-int' => '-[0-9]+'
}

(removed slashes)

or

predefinedRegex = {
    '+int' => /[1-9][0-9]*/,
    'int' => /-?[0-9]+/,
    '-int' => /-[0-9]+/
}

(removed quotes). But then you can skip the whole closure thing.

ormuriauga
+1 for "you can skip the whole closure thing." Unnecessary complexity.
Mark Thomas