2015-07-22 68 views
1

我有這樣的代碼Ruby中未定義的方法'pop'?

def longest_word(sentence) 
    long_word = "" 
    sentence.split(" ").sort_by {|x| x.length} 
    long_word = sentence.pop 

    return long_word 
end 

p longest_word("hello dogs are fast") 

我也得到了該方法「流行」是不確定的,當我嘗試運行它的錯誤。這是否與gemfiles有關?我以爲我已經設置了這些東西。

回答

2

您在一根繩子上sentence,而不是從split字符串數組接收的呼叫陣列方法pop

順便問一下,你的代碼可以簡化爲:

def longest_word(sentence) 
    sentence.split(' ').sort_by(&:length).pop 
end 

p longest_word("hello dogs are fast") 
#=> "hello" 

Demonstration

您還可以使用max_by

sentence.split(" ").max_by(&:length) 

Demonstration

0

你打電話popsentence,這是一個字符串。

你可能想這樣的:

long_word = sentence.split(" ").sort_by {|x| x.length}.pop 
0

splitsort_by不以任何方式改變的變量,它們返回一個新值。因此,如果您不指定此項,sentence仍爲String,"hello dogs are fast",而字符串不具有#pop

sentence = sentence.split(" ").sort_by {|x| x.length} 
相關問題