Ruby 中的 NoMethodError 与比较语句
NoMethodError in Ruby with Comparison Statement
我决定开始学习一些 Ruby 并尝试 Ruby (2.3.0) 中的插入排序版本。但是,当我的程序检查以查看位置以及是否交换值时,它 returns '>' 的 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
我知道这可能是一件微不足道且非常简单的事情,但我无法在这里或其他地方找到问题的解决方案,我们将不胜感激!
修改了你的版本
def sort(input, valueAmount)
for i in 1...valueAmount # Added a dot
j = i
while j >= 0 and input[j - 1] > input[j] # >= instead of >
input[j], input[j - 1] = input[j - 1], input[j]
j += -1
end
end
#Output loop
for i in 0...valueAmount # Added a dot
puts "Sort Value #{i} = #{input[i]}" #Outputs the sorted array to the console
end
end
这是我的版本(没有输出)
def insertion_sort!(ary)
return ary if ary.size < 2
1.upto(ary.size - 1) do |i|
i.downto(0) do |j|
break if ary[j - 1] <= ary[j]
ary[j - 1], ary[j] = ary[j], ary[j - 1]
end
end
ary
end
我决定开始学习一些 Ruby 并尝试 Ruby (2.3.0) 中的插入排序版本。但是,当我的程序检查以查看位置以及是否交换值时,它 returns '>' 的 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
我知道这可能是一件微不足道且非常简单的事情,但我无法在这里或其他地方找到问题的解决方案,我们将不胜感激!
修改了你的版本
def sort(input, valueAmount)
for i in 1...valueAmount # Added a dot
j = i
while j >= 0 and input[j - 1] > input[j] # >= instead of >
input[j], input[j - 1] = input[j - 1], input[j]
j += -1
end
end
#Output loop
for i in 0...valueAmount # Added a dot
puts "Sort Value #{i} = #{input[i]}" #Outputs the sorted array to the console
end
end
这是我的版本(没有输出)
def insertion_sort!(ary)
return ary if ary.size < 2
1.upto(ary.size - 1) do |i|
i.downto(0) do |j|
break if ary[j - 1] <= ary[j]
ary[j - 1], ary[j] = ary[j], ary[j - 1]
end
end
ary
end