2017-01-14 110 views
1

我正在尝试编写一个程序,它接收一个字符串并输出该字符串中最长的单词。现在,我知道我的代码看起来很毛茸茸,但我对Ruby语言很新,所以请耐心等待。我不明白在这个问题上给出的任何其他解释。我不是在寻找答案。我只想让一位善良的人向我解释为什么我的程序在第16行停止了,并且问题标题中提到了问题。谢谢,麻烦您了!Ruby:未定义的方法'长度'为零:NilClass(NoMethodError)

# longest_word.rb 
# A method that takes in a string and returns the longest word 
# in the string. Assume that the string contains only 
# letters and spaces. I have used the String 'split' method to 
# aid me in my quest. Difficulty: easy. 

def longest_word(sentence) 
    array = sentence.split(" ") 

    idx = 0 
    ordered_array = [] 

    puts(array.length) 

    while idx <= array.length 
    if (array[idx].length) < (array[idx + 1].length) 
     short_word = array[idx] 
     ordered_array.push(short_word) 
     idx += 1 
    elsif array[idx].length > array[idx + 1].length 
     long_word = array[idx] 
     ordered_array.unshift(long_word) 
     idx += 1 
    else l_w = ordered_array[0] 
     return l_w 
    end 
    end 
end 

puts("\nTests for #longest_word") 
puts(longest_word("hi hello goodbye")) 
+1

请在您的文章的身体最小的代码示例。图片不是很好的帮助,因为我们无法将它们复制到我们自己的环境中并运行它们。 –

+2

当您发布代码图片而不是发布代码时,您会强制用户输入全部内容以帮助您。你真的认为这是一个很好的态度吗? –

+1

...链接打算被打破。在这里发布代码,它将永远活着。这些建议适合您编辑您的问题,并用您的代码替换链接。 –

回答

0

在while循环中的某个点,您将进入一个状态,其中idx指向数组中的最后一项。此时,要求array[idx+1]返回nil,并且NilClass没有方法'长度'

简单的修复方法是更改​​while循环条件,以便idx+1始终在数组内。

0

我可以推荐一个更简短的解决方案。

words1= "This is a sentence." # The sentence 

words2 = words1.split(/\W+/) # splits the words by via the space character 

words3 = words2.sort_by {|x| x.length} #sort the array 

words3[-1] #gets the last word 

def longest_word(sentence) 
sentence.split(/\W+/).sort_by {|x| x.length}[-1] 
end 
相关问题