我尝试为Chris Pine 教程第 7 章编写自己的字母搜索,并且我想实现一个二进制方法。字符串输入没有有效性,所以我不知道整数与字符串混合会发生什么,但我的想法是只为字符串列表执行此操作。
#get list of strings
puts "type words to make a list. type 'exit' to leave program."
x = ()
list = []
while x.to_s.upcase != 'EXIT'
x = gets.chomp
list.push(x)
end
list.pop
#binary method
nano = list.length
half= list.each_slice(nano/2).to_a
left = half[0]
right = half[1]
nanol=left.length
nanor=right.length
#initialize results array
A = []
for i in 0..nano-1
smallest_left = left.min
smallest_right = right.min
#no difference with this commented out or not
#if nanol==0
# A<<smallest_right
#end
#if nanor==0
# A<<smallest_left
#end
#error message points to the line below (rb:44)
if smallest_left<smallest_right
A << smallest_left
print A
left.pop[i]
elsif smallest_left>smallest_right
A << smallest_right
print A
right.pop[i]
else
print A
end
end
对于 input = ['z','b','r','a'] 我可以看到列表在错误中排序:
["a"]["a", "b"]["a", "b", "r"] rb:44:in `<': comparison of String with nil failed (ArgumentError)
请帮我看看我的错误:)提前谢谢!