Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation Tree and other data structure with ruby [closed]

Tags:

ruby

I am new Ruby programmar. when I was in C++ I could implement data structures with pointer but now in Ruby I don't know how can I implement these data structures ( for example tree ). Can someone help me ( for example introduce me a good reference or take a good example ). Special thanks.

like image 798
amir amir Avatar asked Aug 28 '11 21:08

amir amir


1 Answers

Ruby doesn't have nor need pointers since most things are simply passed by reference.

> a = "hello"
> b = a
> a.object_id == b.object_id
=> true 

In its simplest form a tree node could just be a struct, with a parent and a left and right sibling:

> Node = Struct.new(:parent, :left, :right)
> root = Node.new
> n1   = Node.new(root, "hello", "world")
> root.left = n1
...

> root.left.left
=> "hello"
> root.left.right
=> "world"

For more complete implementations you could look at for example:

RubyTree:
http://rubytree.rubyforge.org/rdoc/

SimpleTree:
https://github.com/ealdent/simple-tree/blob/master/lib/simple_tree.rb

like image 108
Casper Avatar answered Nov 03 '22 01:11

Casper