Question

I just started learning Ruby and I ran into a problem today.

numResults = /\d+/.match(ie.div(:id, 'results_label').text)
puts "Results found: "+numResults.to_s

while(numResults > 0)
.
. some more code
.

I get this error in my output:

Exception: undefined method `>' for #<MatchData:0x424c6d4>

Which is really strange because I made a while loop in IRB and it worked fine. I can't get the code inside the loop to execute because the program sticks at the condition.

Anyone know what's wrong?

Was it helpful?

Solution

numResults is a MatchData object and can't be compared with the > method. You need to convert it to a string, then convert the string to a number:

while(numResults.to_s.to_i > 0)

OTHER TIPS

In cases where the string doesn't match the expression, numResults will be nil

so if thats what you are testing for, you'll want

while( !numResults.nil? ){ 

}

In cases where the string does match the expression, numResults won't be nil , and additionally, will contain the number of matches ( only 1 at most here because you don't have a repeating match ) in numResults.size

Also, other posters need to keep in mind that numResults contains no number of matches found, but contains the value of the actual match from the text data.

While

numResults.to_s.to_i 

Might work, its only due to the grace of nil.to_s.to_i == 0.

If you were relying on numResults to be anything meaningful in terms of regex match count, you were looking in the wrong place.

Try changing your while condition to:

while(numResults.to_i > 0)

This will force the numResults to an integer. It looks like it is being returned as a string from you regexp matcher.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top