2015-05-18 59 views
0
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長度 '的零:NilClass(NoMethodError)
從longest_word.rb:15:在`'

上爲什麼任何信息這是發生將是巨大的

+0

而idx

回答

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

你的代碼是不是 'rubyesk',我寧願:

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)

相關問題