【问题标题】:Ruby access element from each_with_index来自 each_with_index 的 Ruby 访问元素
【发布时间】:2017-05-28 00:43:42
【问题描述】:

如何仅打印从最后一行调用返回的索引:

def collatz_sequence( seed )
    sequence = [ seed ]
    n = seed

    while 1 != n
        n = ( 0 == n % 2 ) ? n/2 : 3*n + 1
        sequence.push( n )
    end

    return sequence
end

limit = 1_000_000
puts ( 1..limit ).map { | i | collatz_sequence( i ).length }.each_with_index.max

【问题讨论】:

  • 您的问题不清楚。 “这个电话”是什么意思?您的代码中有 12 个不同的调用站点。
  • 你想做什么?
  • 最后一行调用,我试图只返回索引。现在正在返回索引和元素。

标签: arrays ruby indexing


【解决方案1】:

目前它返回一个包含元素和索引的数组,索引在最后。

puts ( 1..limit ).map {| i | collatz_sequence( i ).length}.each_with_index.max.last

【讨论】:

  • 谢谢,帮了我很多忙
猜你喜欢
  • 1970-01-01
  • 2011-03-21
  • 2016-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
相关资源
最近更新 更多