【问题标题】:Ruby: Undefined method 'length' for nil:NilClass (NoMethodError)Ruby:nil:NilClass(NoMethodError)的未定义方法“长度”
【发布时间】:2017-05-30 02:21:35
【问题描述】:

我正在尝试编写一个程序,它接收一个字符串并输出该字符串中最长的单词。现在,我知道我的代码看起来很麻烦,但我对 Ruby 语言还很陌生,所以请耐心等待。我不理解有关此问题的任何其他解释。我不是在寻找答案。我想要的只是让一个善良的人向我解释为什么我的程序在第 16 行停止并出现此问题标题中所述的问题。请,谢谢!

# 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"))

【问题讨论】:

  • 请在您的帖子正文中包含一个最小的代码示例。图片帮助不大,因为我们无法将它们复制到我们自己的环境中并运行它们。
  • 当您发布代码的图像时,不是发布您的代码,而是强迫人们全部输入以帮助您。你真的认为这是一种很好的态度吗?
  • ...和链接意味着被破坏。在此处发布代码,它将永远存在。这些建议是供您编辑问题并将链接替换为您的代码。
  • @EddeAlmeida 我很抱歉,我是堆栈溢出的菜鸟。从今天开始,我将包含代码。
  • 谢谢。我们想提供帮助,所以请帮助我们帮助您。

标签: ruby methods undefined nomethoderror


【解决方案1】:

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

简单的解决方法是更改​​ while 循环条件,使 idx+1 始终在数组中。

【讨论】:

    【解决方案2】:

    我可以推荐一个更短的解决方案吗?

    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
    

    【讨论】:

      猜你喜欢
      • 2021-07-07
      • 2021-08-05
      • 1970-01-01
      • 2013-04-24
      • 2015-05-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      相关资源
      最近更新 更多