[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

parse a tree

Haris Bogdanovic

3/4/2009 2:52:00 AM

Hi.

How can I parse a tree (arrays within arrays), for example a tree of
strings, to print all strings ?

Thanks.


4 Answers

Michael Malone

3/4/2009 3:17:00 AM

0

Haris wrote:
> Hi.
>
> How can I parse a tree (arrays within arrays), for example a tree of
> strings, to print all strings ?
>
> Thanks.
>
>
>
>
tree walking hints at a recursive routine...

def tree_walk(array)
array.each do |item|
if item.class == Array
tree_walk(item)
else
puts item
end
end
end

or for the one-liners among us
def tree_walk(array)
array.each { |item| (item.class == Array)? tree_walk(item) : puts item }
end

However, I don't reccomend testing on the item.class. I can't explain
why very well, but it seems wrong to me. Maybe someone else can...?

=======================================================================
This email, including any attachments, is only for the intended
addressee. It is subject to copyright, is confidential and may be
the subject of legal or other privilege, none of which is waived or
lost by reason of this transmission.
If the receiver is not the intended addressee, please accept our
apologies, notify us by return, delete all copies and perform no
other act on the email.
Unfortunately, we cannot warrant that the email has not been
altered or corrupted during transmission.
=======================================================================


Peña, Botp

3/4/2009 3:37:00 AM

0

From: Michael Malone [mailto:michael.malone@tait.co.nz]=20
#..
# def tree_walk(array)
# array.each { |item| (item.class =3D=3D Array)?=20
^^^^^^^^^^^^^^^^^^^^ =20
item.is_a? Array

# tree_walk(item) : puts item }
# end


note that the above tree_walk is equivalent to,=20

puts array



Brian Candler

3/4/2009 9:08:00 AM

0

Michael Malone wrote:
> However, I don't reccomend testing on the item.class. I can't explain
> why very well, but it seems wrong to me. Maybe someone else can...?

I think it's fine. You need some way to distinguish between a leaf node
and an inner node, and how you do that depends on how your data
structure is built.

Here, the assumption is that inner nodes are Arrays and leaf nodes are
anything else.
--
Posted via http://www.ruby-....

Robert Klemme

3/4/2009 11:18:00 AM

0

On 04.03.2009 03:51, Haris Bogdanoviæ wrote:
> How can I parse a tree (arrays within arrays), for example a tree of
> strings, to print all strings ?

Do you want to _parse_ or _print_? This is totally unclear to me. For
displaying nested structures for debugging purposes, pp will do

require 'pp'

a = [...] # nested
pp a

If you want to parse: you did not provide how the input looks like so
nobody could help you with that.

Kind regards

robert