为什么方法会删除数组中的元素?

时间:2013-12-28 19:54:14

标签: ruby arrays sorting

我正在尝试使用递归创建我自己的.sort方法作为红宝石书中的练习,并且出于某种原因他们还没有教我太空飞船运营商。我的代码用于获取最小值 - apple - 并将其放入已排序的数组中,它甚至使用递归重复,并重置数组以重复该过程以添加第二个最小的单词。问题是由于某种原因它删除了最小的词 - 苹果 - 我无法弄清楚原因。我知道我的想法 - 在其他myArray.length == 1语句中,当我从数组中弹出元素时,但为什么它也会从sortedArray中删除?

sortedArray以值apple结束,然后当它进行递归时,它应该是sortedArray = ['apple','banana'...]但它会删除apple,然后它会删除banana等...直到我最终使用sortedArray = ['昆西']

我尝试将我的数组移动到多个位置,并且我尝试在多个位置添加到sortedWords数组,但它总是删除或重置sortedWords数组。

看起来我真的很亲密,因为我已经完成了按字母顺序排列的工作。如何让它将所有项添加到sortedWords数组?

ArrayofWords = ['cat', 'dog', 'bat', 'elephant', 'apple', 'banana', 'quincy', 'boo']

# Why is it deleting, or replacing my sortedWords array? If you run this code you will     notice that the sortedWords array
# is giving me the smallest word in the array, but then I add the recursive part, and somehow the previous smallestword
#gets deleted... but I have never in any part of my code say delete or replace the sorted    array...

def sortTheArray myArray
  unsortedWords = []
  sortedWords   = []
  smallestValue = ''

  while myArray.length != 0
    if myArray.first < myArray.last
      unsortedWords.push(myArray.last)
        myArray.pop
    elsif myArray.first > myArray.last
      unsortedWords.push(myArray.first)
      myArray.delete_at(0)
    else myArray.length == 1
      sortedWords.push(myArray.first)
      myArray.pop # This is my problem area I think???
    end # if else


    #puts 'sorted words'  
    #puts sortedWords
    #puts 'unsortedWords'
    #puts unsortedWords
  end # while

  puts 'sorted words'  
  puts sortedWords
  puts 'unsortedWords'
  puts unsortedWords

  myArray = unsortedWords

  while myArray.length > 0
    sortTheArray myArray
  end #while

end # sortTheArray
sortTheArray ArrayofWords

大多数这些看跌期权都没有必要,我只想弄清楚问题出在哪里。

1 个答案:

答案 0 :(得分:1)

您的代码遇到了很多问题。例如,您似乎希望在此方法的调用中累积已排序的单词,但是您在方法块的开头将sorted_words重新初始化为[]

我建议首先尽可能简单地用英语表达你的递归解决方案,然后设法实现它。

例如,以下是一种似乎与您尝试做的一致的方法:

def sorted_array(array)
  lowest_value prepended to the sorted_value of the array with the lowest_value removed
end

我正在分享上述内容,因为看起来你是Ruby的新手,只是以惯用的方式实现上述内容将是一个很好的挑战。