如何在Ruby中将数组放入数组中

时间:2015-04-06 23:12:44

标签: ruby arrays

我正在做一个家谱。所以,我正在形成从最老的家庭成员到最新的家庭成员的订单。

为此,我要形成一个具有最终树结构的数组,然后我只打印结果。

在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中,我想做这样的事情。 抱歉我的英文。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

我建议使用RubyTree,而不是数据结构。有几个优点:

  • 您可能需要执行的一些查询已经有效实施
  • 命名约定与您的域(父/祖父母/兄弟姐妹/子女等)匹配
  • 它会大大缩短您的代码并使其更易于阅读
  • 有遍历和打印树的内置方法

以下是文档的摘录,可以帮助您了解它:

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 - 非常易读。