def longest_word(string)
words = string.split
idx = 0
while idx < words.length
if words[idx].length > words[idx + 1].length
longest = words[idx]
else
longest = words [idx + 1]
end
idx += 1
end
return longest
end
puts(longest_word("peas rambling tattoo") == "rambling")
不断收到错误消息
longest_word.rb:5:longest_word': undefined method
长度'为nil:NilClass(NoMethodError)
来自longest_word.rb:15:在''
关于为什么会发生这种情况的任何信息都会很棒
答案 0 :(得分:6)
words.length
返回元素数,但索引以0开头。
您需要(words.length - 1)
def longest_word(string)
words = string.split
idx = 0
while idx < (words.length - 1)
if words[idx].length > words[idx + 1].length
longest = words[idx]
else
longest = words [idx + 1]
end
idx += 1
end
return longest
end
puts(longest_word("peas rambling tattoo") == "rambling")
您的代码不是&#39; rubyesk&#39;,我更愿意:
def longest_word(string)
longest = ''
string.split.each do |word|
longest = word.length > longest.length ? word : longest
end
return longest
end
puts(longest_word("peas rambling tattoo") == "rambling")
或者更好:
def longest_word(string)
longest = ''
string.split.each do |word|
longest = word if word.length > longest.length
end
return longest
end
puts(longest_word("peas rambling tattoo") == "rambling")
您还可以使用max_by
来获取更短的代码:
def longest_word(string)
string.split.max_by{|word| word.length}
end
puts(longest_word("peas rambling tattoo") == "rambling")
或者更短string.split.max_by(&:length)