这是一个二进制搜索算法。的a和b是它正在工作的数组索引,找到相当的是它正在搜索的字符串,并且字符串数组是一个字符串数组。不幸的是,每当我尝试运行这个功能,我得到以下语法错误时间:
未定义的方法`包括哪些内容? 1:Fixnum对象(NoMethodError)`但是,这不是一个长整数。我是pretty新的Ruby,所以我可以很容易地失去了一些东西明显。任何建议?
这是我在这里声明字符串数组:(Netbeans的说,它是一个数组)
字符串= Array.new newstring = 直到newstring ==不吗 newstring = gets.chomp 字符串[strings.size] = newstring 结束解决方案
的传递到你的函数字符串数组实际上不是一个字符串数组,而只是一个简单的串。在一个字符串使用 [] 方法返回给定位置的字符的字符code,作为一个Fixnum对象;所以字符串数组[K]在返回字符串中位置k的字符的字符code。而作为错误说,Fixnum对象不具有包括哪些内容?。
即使字符串数组的已的字符串数组,我不知道你为什么会做字符串比较与包括哪些内容?。 包括哪些内容?是找出是否在数组中存在的项目。比较字符串,只需使用 == 。
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 endThis 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 stringarray that 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 an include?.
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 ==.
更多推荐
问题在红宝石二进制搜索算法
发布评论