从数组中查找最大数字并将字符串与它们相关联

Jam*_*ell 2 ruby arrays

我有两个包含人物信息的数组:

brad = ["Brad", 16]
andrew = ["Andrew", 43]
Run Code Online (Sandbox Code Playgroud)

可以通过以下方式找到更大的数字:

max_num = [brad[1], andrew[1]].max
Run Code Online (Sandbox Code Playgroud)

我希望将名称与最大值匹配,所以我可以说

puts "The max is #{max_num} and the record setter is #{name}"
Run Code Online (Sandbox Code Playgroud)

我将如何实现这一目标?这必须适用于列出的两个以上的数组,因此答案if max_num == brad[1] else等不起作用.

xda*_*azz 5

你可以得到:

[brad, andrew].max_by { |k,v| v } # => ["Andrew", 43]
Run Code Online (Sandbox Code Playgroud)

所以

name, max_num = [brad, andrew].max_by { |k,v| v }
puts "The max is #{max_num} and the record setter is #{name}"
Run Code Online (Sandbox Code Playgroud)