来自each_with_index的Ruby访问元素

时间:2017-01-12 19:14:48

标签: arrays ruby indexing

如何只打印从上一行调用返回的索引:

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

1 个答案:

答案 0 :(得分:0)

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

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