我正在使用Ruby学习编程,我不得不构建自己的排序方法。
我正在努力弄清楚为什么recursive_sort中的比较方法会抛出错误
chapter10.rb:120:in `block in recursive_sort': undefined method `<' for ["zebra"]:Array (NoMethodError)
但这很好用......
lowest = 'zebra'
if 'cat' < 'zebra'
lowest = 'cat'
end
puts lowest
有人可以把正确的方向放在可以帮助我绕过这个的东西上吗?谢谢!
puts 'Sorting Program with recursion v1.0'
# Keep two more lists around
# One for already-sorted words
# One for still - unsorted words
# Find the smallest word in the unsorted list
# push it into the end of the sorted_array
def sort some_array
recursive_sort some_array, []
end
def recursive_sort unsorted_array, sorted_array
lowest = unsorted_array[0]
unsorted_array.each do |uns|
if uns < lowest
lowest = uns
end
end
puts lowest
end
# Get a list of unsorted words into an array
orig_array = []
word = 'placeholder'
puts 'Enter a list of words to be sorted. Press enter when done.'
while word != ''
word = gets.chomp
orig_array.push [word]
end
orig_array.pop
puts 'This is the output of the built in sort method.'
orig_array.sort.each do |un|
puts un
end
puts 'This is the output of Rick\'s sort method.'
sort orig_array
答案 0 :(得分:2)
orig_array.push [word]
在这里,您实际上是将数组推入数组,以便orig_array
成为
[["word 1"], ["word 2"], ["word 3"], ...]
移除[]
周围的word
以解决此问题,或将.push
更改为+=
或.concat
,这会将两个阵列粘合在一起。< / p>