2011-08-28 103 views
7

我是新的Ruby程序。當我在C++中時,我可以用指針實現數據結構,但現在在Ruby中我不知道如何實現這些數據結構(例如樹)。 有人可以幫助我(例如向我介紹一個很好的參考或舉一個好例子)。 特別感謝。用ruby實現樹和其他數據結構

+0

想要關聯ActiveRecord對象還是僅面向Ruby的問題? – apneadiving

+0

不好意思,我在你的評論中沒有像ActiveRecoed這樣的表達意思。你能更清楚地解釋一下嗎? –

+0

ActiveRecord是Rails的Orm – apneadiving

回答

10

Ruby沒有也不需要指針,因爲大多數事情只是通過引用傳遞。

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

的最簡單形式的樹節點可能只是一個結構,有父母和一個左和右兄弟:

> 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" 

需要更完整的實現,你可以看一下,例如:

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

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