【发布时间】:2016-07-15 03:55:42
【问题描述】:
我决定开始学习一点 Ruby 并尝试使用 Ruby (2.3.0) 中的插入排序版本。但是,当我的程序检查位置以及是否交换值时,它会为“>”返回 NoMethodError。更具体地说:
./rubyInsertSort.rb:28:in `block in sort': undefined method `>' for 1..4:Range (NoMethodError)
from ./rubyInsertSort.rb:26:in `each'
from ./rubyInsertSort.rb:26:in `sort'
from ./rubyInsertSort.rb:22:in `main'
from ./rubyInsertSort.rb:40:in `<main>'
这里是排序方法的代码:
def sort(input, valueAmount)
for i in 1..valueAmount
j = i
while j > 0 and input[j - 1] > input[j]
input[j], input[j - 1] = input[j - 1], input[j]
j += -1
end
end
#Output loop
for i in 1..valueAmount
puts "Sort Value #{i} = #{input[i]}" #Outputs the sorted array to the console
end
end
我知道这可能是一件微不足道且非常简单的事情,但我在这里或其他地方找不到问题的解决方案,我们将不胜感激!
【问题讨论】:
-
它对我来说很好用...尝试更多地使用 ruby-wise
(1..valueAmount).each do |i|看看它是否有效 -
请给出导致此错误的
input和valueAmount的值。 -
valueAmount 是一个整数值,用于存储要存储的值的数量,输入是一个 size[valueAmount] 的数组,用于存储值的列表。在这种情况下,输入值为:2、7、4 和 9
-
@RubyRacer 我已经尝试过您的修复,现在在运行 ../rubyInsertSort.rb:26:in
sort': undefined methodeach' for 3:Fixnum (NoMethodError) 时收到不同的错误 -
我无法复制您的错误。它实际上对我来说运行良好。不过,您的错误消息非常时髦。最初的错误说您正在尝试在一系列数字上使用
>,但我没有看到您在排序方法中这样做。您的第二个错误说未定义方法each。您需要在数组上调用each,如果您在数组或哈希以外的其他对象上调用它,通常会弹出此错误。您的解决方案有效,我可以提交它的重构版本,但我不知道您为什么会收到这些错误。也许它与您的环境或 ruby 版本有关?