Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Nuby Array questions - each iterates nested arrays?

253 views
Skip to first unread message

Ed Howland

unread,
Oct 26, 2005, 1:16:39 PM10/26/05
to
a=[[1, 2, 3], [4, 5, 6]]
=> [[1, 2, 3], [4, 5, 6]]
a.length
=> 2
a.each {|x| puts x}
1
2
3
4
5
6
=> [[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


Peter Ertl

unread,
Oct 26, 2005, 1:22:44 PM10/26/05
to
a.flatten.each { |x| p x}

:-)

> --- Ursprüngliche Nachricht ---
> Von: Ed Howland <ed.ho...@gmail.com>
> An: ruby...@ruby-lang.org (ruby-talk ML)
> Betreff: Nuby Array questions - each iterates nested arrays?
> Datum: Thu, 27 Oct 2005 02:16:39 +0900

Berger, Daniel

unread,
Oct 26, 2005, 1:23:07 PM10/26/05
to
> -----Original Message-----
> From: Ed Howland [mailto:ed.ho...@gmail.com]
> Sent: Wednesday, October 26, 2005 11:17 AM
> To: ruby-talk ML
> Subject: Nuby Array questions - each iterates nested arrays?
>
>
> a=[[1, 2, 3], [4, 5, 6]]
> => [[1, 2, 3], [4, 5, 6]]
> a.length
> => 2
> a.each {|x| puts x}
> 1
> 2
> 3
> 4
> 5
> 6
> => [[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.

Actually, it doesn't. It just looks that way because of the way 'puts'
works with arrays. Try 'ruby -e "puts [1,2,3]"' to see what I mean.
See the docs on IO.puts for more details.

To see what's really happening replace 'puts' with 'p' (inspect) in your
example.

Regards,

Dan


Peter Ertl

unread,
Oct 26, 2005, 1:27:34 PM10/26/05
to
another possible solution:

class Array
def each_recursive(&block)
each do |x|
if Enumerable === x
x.each_recursive(&block)
else
yield x
end
end
end
end

a=[[1, 2, 3], [4, 5, 6]]

a.each_recursive { |x| p x}

> --- Ursprüngliche Nachricht ---
> Von: "Peter Ertl" <pe...@gmx.org>
> An: ruby...@ruby-lang.org (ruby-talk ML)
> Betreff: Re: Nuby Array questions - each iterates nested arrays?
> Datum: Thu, 27 Oct 2005 02:22:44 +0900

Markus Koenig

unread,
Oct 27, 2005, 2:26:42 PM10/27/05
to
Ed Howland wrote:

> 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

0 new messages