我有两个数组,一个存储候选名称,另一个存储所述候选人的投票数.我正在尝试打印最大票数和相应候选人的姓名; 而不是诸如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 }
Run Code Online (Sandbox Code Playgroud)
我成功获取了最大值所在的索引,但是如何使用该索引来匹配候选数组的索引以便打印名称而不是索引?
puts votes.zip(candidates).max_by(&:first)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
212 次 |
| 最近记录: |