2017-09-13 78 views
-1

如何在ruby中查找数组中最长的名称。这是我试过的:试图在Ruby中查找数组中最长的字符串

people = ["john", "clark", "stan", "mike", "nick", "devon"] 


def find_longest_name(people) 
    longest_name = nil 
    longest_name_length = -1 
    people.each do |friend| 
    if friend.length > longest_name_length 
     longest_name = frined 
     longest_name_length = friend.length 
    end 
    end 
return longest_name 
end 
puts "#{longest_name_length}" 

我得到一个错误,说我有一个未定义的变量。

+4

'frined'!='friend' – axiac

+0

*你找哪家*错误?请阅读* whole *错误,它会*告诉*你a)*完全*在哪里找到未定义的变量和b)该变量的*精确*名称是什么。看看这个名字。你1000000%确定这是变量的名称? –

+0

在'puts“#{longest_name_length}”'中,'longest_name_length'在方法定义中定义。将无法从外部访问。 –

回答

4

试试这个

people.max_by(&:length) 

你在这行

longest_name = frined 
0

拼写错误friendfrined为了获得最大的

people.map(&:length).max 

对于最低

people.map(&:length).min 

如果你想为长字符串最大

h = {} 
people.map{|a| h[a]= a.length} 
h.key(h.values.max) 
相关问题