我有两个数组,一个存储候选人的名字,另一个存储候选人的票数。我正在尝试打印最大票数和相应候选人的姓名;而不是输出92, 4
((票数,候选人索引)等,而是输出92, John
。
这与我要做的很接近:
puts "Candidates, index order: 0, 1, 2, 3, 4"
candidates.each { |x| puts x }
puts "Votes, index order: 0, 1, 2, 3, 4"
votes.each { |y| puts y }
votes.delete(nil)
puts "Maximum number of votes, followed by candidates array index."
puts votes.each_with_index.max { |x,y| x <=> y }
我已成功获取最大值所在的索引,但是如何使用该索引来匹配候选人数组的索引以打印名称而不是索引?
puts votes.zip(candidates).max_by(&:first)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句