我正在尝试编写一个程序,它接收一个字符串并输出该字符串中最长的单词。现在,我知道我的代码看起来很毛茸茸,但我对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"))
请在您的文章的身体最小的代码示例。图片不是很好的帮助,因为我们无法将它们复制到我们自己的环境中并运行它们。 –
当您发布代码图片而不是发布代码时,您会强制用户输入全部内容以帮助您。你真的认为这是一个很好的态度吗? –
...链接打算被打破。在这里发布代码,它将永远活着。这些建议适合您编辑您的问题,并用您的代码替换链接。 –