我尝试了这里推荐的解决方案-在Ruby中,最干净的方法是获取数组中最大值的索引?
array = [nil, nil, nil, nil, nil, 0.9655172413793104, nil, nil]
idx = array.each_with_index.max[1]
但是有一些例外:
ArgumentError: comparison of Array with Array failed
from (irb):4:in `each'
from (irb):4:in `each_with_index'
from (irb):4:in `each'
from (irb):4:in `max'
from (irb):4
from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.3/lib/rails/commands/console.rb:65:in `start'
from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.3/lib/rails/commands/console_helper.rb:9:in `start'
from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.3/lib/rails/commands/commands_tasks.rb:78:in `console'
from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.3/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
from /Users/davea/.rvm/gems/ruby-2.4.0/gems/railties-5.0.3/lib/rails/commands.rb:18:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
如果nil
要从结果中省略,则可以使用:
array.index(array.compact.max)
或者,如果您希望将nil
s视为零,请先将它们转换为Float
s:
array.index(array.map(&:to_f).max)
如果出现平局,这将返回第一个最大值的索引。您还可以使用获取最后的索引Array#rindex
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句