试图在Ruby中找到数组中最长的字符串

时间:2017-09-13 14:35:59

标签: 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}"

我收到一条错误消息,说我有一个未定义的变量。

2 个答案:

答案 0 :(得分:4)

试试这个

people.max_by(&:length)

您在此行<{1}}误导了friend

frined

答案 1 :(得分:0)

最大

people.map(&:length).max

至少

people.map(&:length).min

如果你想要最大字符串的长度

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