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?
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.
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 .
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With