2015-04-06 57 views
0

我正在做一個家族樹。所以,我正在組織從最老到最新的家庭成員的順序。如何將數組放入Ruby中的數組

爲此,我正在形成一個具有最終樹結構的數組,然後我只打印結果。

在PHP中我可以做這樣的事情:

Array(
'member1' => [ 
    'sub_member11' => [ 
    ['sub_sub_member111' => some_value_of_sons], 
    ['sub_sub_member112' => some_value_of_sons] 
    ], 
    ['sub_member12' => some_value_of_sons] 
], 
'member2' => [ 
    ['sub_member21' => some_value_of_sons], 
    ['sub_member22' => some_value_of_sons] 
] 
) 

在Ruby中,我願做這樣的事情。 對不起,我的英語。

+0

在Ruby中會被認爲是散列,但無論哪種方式,在Ruby中都很容易。你有嘗試過什麼嗎?查找「Ruby哈希」。 – lurker

+2

您可以使用散列或其他大數據結構,但您會失去Ruby的表現力。我建議創建一個類或使用現有的類,如RubyTree。 –

+1

@MarkThomas有最好的答案。如果您正在構建家族樹,則應該使用樹形數據結構。那麼你的數據自然會映射到數據結構。 –

回答

0

我會建議使用RubyTree對於這一點,而不是數據structu回覆。有幾個優點:

  • 一些疑問,你可能需要做的已經有效地實現
  • 的命名約定相匹配您的域名(父母/祖父母/兄弟姐妹/孩子等)
  • 將縮短你的代碼相當,並使其更容易閱讀
  • 有內置的方式來遍歷和打印樹

下面是從文檔的摘錄,這將有助於你得到的費用l對於它:

require 'tree'  

# ..... Create the root node first. Note that every node has a name and an optional content payload. 
root_node = Tree::TreeNode.new("ROOT", "Root Content") 
root_node.print_tree 

# ..... Now insert the child nodes. Note that you can "chain" the child insertions for a given path to any depth. 
root_node << Tree::TreeNode.new("CHILD1", "Child1 Content") << Tree::TreeNode.new("GRANDCHILD1", "GrandChild1 Content") 
root_node << Tree::TreeNode.new("CHILD2", "Child2 Content") 

# ..... Lets print the representation to stdout. This is primarily used for debugging purposes. 
root_node.print_tree 

# ..... Lets directly access children and grandchildren of the root. The can be "chained" for a given path to any depth. 
child1  = root_node["CHILD1"] 
grand_child1 = root_node["CHILD1"]["GRANDCHILD1"] 

# ..... Now lets retrieve siblings of the current node as an array. 
siblings_of_child1 = child1.siblings 

# ..... Lets retrieve immediate children of the root node as an array. 
children_of_root = root_node.children 

注意該示例顯示了節點的內容作爲一個字符串,但你可以把任何物體存在。您可能需要創建一個值對象來保存所有的元數據。

class FamilyMember 
    attr_accessor :name :last_name, :maiden_name, :birth_date, :etc 
end 

希望在做完所有這些之後,您的代碼將更像uncle_bob.children.first.birth_date - 非常可讀。

3

我認爲您正在尋找Ruby的Hash數據類型。您可以創建一個新的哈希使用的語法如下:

{ key1 => value1, key2 => value2 } 

所以,你可以通過寫作讓你需要的數據的哈希它:

hash = { 
    'member1' => { 
    'sub_member11' => { 
     'sub_sub_member111' => some_value_of_sons, 
     'sub_sub_member112' => some_value_of_sons, 
    }, 
    'sub_member12' => some_value_of_sons, 
    }, 
    'member2' => { 
    'sub_member21' => some_value_of_sons, 
    'sub_member22' => some_value_of_sons, 
    }, 
} 

散列在Ruby程序中使用非常普遍,所以它會還清了解他們,閱讀文檔:

http://ruby-doc.org/core/Hash.html