Question

I'm trying to write some simple Ruby code to test the psuedo-code I wrote for an exercise. I encounter the error "linearsort.rb:14:in <main>': undefined methodlinearsearch' for main:Object (NoMethodError)".

Basically I just want to search through a sequence of numbers looking for a value v, and if so return the position in the sequence, if not to return nil.

I've reviewed several questions containing the same error however I've found none that I can draw any meaningful lesson from. Please help...

class Array
    def linearsearch(a, v)
        0.upto(a.length-1) do |j|
            if a[j] == v
                j
            end
        nil
        end
    end
end

dis = [0,2,5,1,8,9]

print linearsearch(dis, 9)
Was it helpful?

Solution 2

You should invoke linearsearch on an object of type Array, not pass the array as an argument. As it stands, you are invoking linearsearch on the ruby top level, which is an instance of Object, and therefore doesn't have your method defined. Try changing linearsearch to be invoked on an object of type Array, like so

class Array
  def linearsearch(v)
    0.upto(self.length - 1) do |j|
      if self[j] == v
        return j
      end
    end
    nil
  end
end

and invoke it like

dis.linearsearch(9)

OTHER TIPS

I know you said this is for a project, but is there any reason you're not using the native index method?

dis = [0,2,5,1,8,9]
puts dis.index(9) #=> 5
puts dis.index(1) #=> 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top