Nuby Array questions - each iterates nested arrays?

E

Ed Howland

a=3D[[1, 2, 3], [4, 5, 6]]
=3D> [[1, 2, 3], [4, 5, 6]]
a.length
=3D> 2
a.each {|x| puts x}
1
2
3
4
5
6
=3D> [[1, 2, 3], [4, 5, 6]]
a.each_index {|x| puts x}
0
1

Why does each traverse into the inner arrays as well (tried it with 3
and 4 deep?)
Array#length seems to be correct to me and Array#each_index
This seems to happen to collect!, and I'd gather other methods as well.

Convenient, if you want depth first traversal on all arrays. but what
if you just want to iterate in a shallow manner?

Thanks
Ed
 
M

Markus Koenig

Ed said:
Why does each traverse into the inner arrays as well (tried it with 3
and 4 deep?)

This does not happen, but the puts makes it seem so. What really
happens is this:

=> puts [1, 2, 3]
1
2
3
=> puts [4, 5, 6]
4
5
6

Try p though:

=> [[1, 2, 3], [4, 5, 6]].each {|x| p x}
[1, 2, 3]
[4, 5, 6]

Greetings,
Markus
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,184
Messages
2,570,978
Members
47,561
Latest member
gjsign

Latest Threads

Top