简体   繁体   中英

Ruby access element from each_with_index

How I can print only the index returned from the last line call:

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

当前,它返回一个包含元素和索引的Array,索引为last。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM