loops - Ruby's "each" methods not iterating over all items in an array? -


i'm trying out following code:

a = [1,2,3,4]   a.each     puts "removing #{a.last}"     a.pop   end 

but instead of getting 4 numbers popped first 3. indeed, doing puts a.length returns 1 , puts-ing shows element "1" still there.

how need use method correctly? (i'm using ruby 2.0).

i suspect happening because you're iterating on elements of list while modifying list.

try following:

a = [1,2,3,4] until a.empty?   puts "removing #{a.last}"   a.pop end 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -