Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: undefined method `>'

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?

like image 410
Dennis Avatar asked Mar 24 '09 21:03

Dennis


People also ask

What is an undefined method in Ruby?

Undefined method call created a NoMethodError. This is a typical Ruby error that indicates that the method or attribute you are attempting to call on an object has not been declared.

Does Ruby have undefined?

Undefined instance variables are always nil , so you want to check for that. Try the “safe navigator operator” (Ruby 2.3+) which only calls a method if the variable is not nil .

What is no method error in Ruby?

This is a common Ruby error which indicates that the method or attribute for an object you are trying to call on an object has not been defined.

What does NoMethodError mean?

According to The 2022 Airbrake Error Data Report, the NoMethodError is the most common error within projects. As clearly indicated by the name, the NoMethodError is raised when a call is made to a receiver (an object) using a method name that doesn't exist.


2 Answers

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)
like image 140
Paige Ruten Avatar answered Oct 02 '22 21:10

Paige Ruten


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.

like image 22
Kent Fredric Avatar answered Oct 02 '22 19:10

Kent Fredric