Ruby中的并行数组

Jer*_*one 1 ruby

我有两个数组,一个存储候选名称,另一个存储所述候选人的投票数.我正在尝试打印最大票数和相应候选人的姓名; 而不是诸如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)

我成功获取了最大值所在的索引,但是如何使用该索引来匹配候选数组的索引以便打印名称而不是索引?

saw*_*awa 5

puts votes.zip(candidates).max_by(&:first)
Run Code Online (Sandbox Code Playgroud)

  • 最后!我花了太多时间试图解决这个问题.谢谢! (2认同)
  • 这并不一定意味着浪费了时间.顺便说一句,每当你可以使用[Enumerable#zip](http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-zip)和两个大小相等的数组时,你也可以使用[Array] #transpose](http://ruby-doc.org/core-2.2.0/Array.html#method-i-transpose):`[[10,23,6],["Bob","Betty", "Bubba"]] .transpose.max_by(&:first)#=> [23,"Betty"]`.另一种不那么类似Ruby的方式是`mx = votes.max; [mx,candiates [votes.index(mx)]`. (2认同)