Arrays 从数组中找出最大数目并将字符串与之关联
我有两个数组,其中包含有关人员的信息:Arrays 从数组中找出最大数目并将字符串与之关联,arrays,ruby,Arrays,Ruby,我有两个数组,其中包含有关人员的信息: brad = ["Brad", 16] andrew = ["Andrew", 43] 较大的数字可通过以下方式找到: max_num = [brad[1], andrew[1]].max 我想将名称与最大值匹配,这样我就可以说 puts "The max is #{max_num} and the record setter is #{name}" 我将如何实现这一目标?这必须适用于所列的两个以上的数组,因此如果max_num==brad[1]el
brad = ["Brad", 16]
andrew = ["Andrew", 43]
较大的数字可通过以下方式找到:
max_num = [brad[1], andrew[1]].max
我想将名称与最大值匹配,这样我就可以说
puts "The max is #{max_num} and the record setter is #{name}"
我将如何实现这一目标?这必须适用于所列的两个以上的数组,因此如果max_num==brad[1]else等的答案将不起作用。您可以通过以下方式获得:
[brad, andrew].max_by { |k,v| v } # => ["Andrew", 43]
所以
谢谢你@xdazz它成功了,你能解释一下{k,v{v}是什么意思吗?@JamesMitchell这里的
k
将是名字,v
将是数字,max_by num是v
…或者将“max是%s,创纪录者是%d”[brad,andrew]。max_by{k,v}/code>。
name, max_num = [brad, andrew].max_by { |k,v| v }
puts "The max is #{max_num} and the record setter is #{name}"