def binarysearch(a, b, tofind, stringarray)
k=(a+b)/2
if a==b
return nil
end
if (stringarray[k]).include? tofind
return stringarray[k]
end
if (stringarray[k]<=>tofind)==1
binarysearch(a,k,tofind,stringarray)
end
if (stringarray[k]<=>tofind)==-1
binarysearch(k,b,tofind,stringarray)
end
if (stringarray[k]<=>tofind)==0
return stringarray[k]
end
end
This is a binary search algorithm. The a and b are the array indices that it is working on, tofind is a string that it is searching for, and stringarray is an array of strings. Unfortunately, every time that I try to run this function I get the following syntax error:
undefined method `include?' for 1:Fixnum (NoMethodError)`
But this is not a fixnum. I am pretty new to Ruby, so I could easily be missing something obvious. Any advice?
This is where I declare stringarray: (Netbeans says that it is an array)
strings=Array.new
newstring=""
until newstring=="no" do
newstring=gets.chomp
strings[strings.size]=newstring
end
The
stringarraythat is passed to your function is not actually an array of strings, but just a simple string. Using the[]method on a string returns the character code of the character at the given position, as a Fixnum; so stringarray[k] returns the character code of the character at position k in the string. And as the error says, Fixnum does not have aninclude?.Even if stringarray was an array of strings, I’m not sure why you would do string comparisons with
include?.include?is for finding out if items exist in an array. To compare strings, just use==.