Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
可以在Ruby中检索哈希中元素的属性,但不能检索元素本身_Ruby_Performance_Hash - Fatal编程技术网

可以在Ruby中检索哈希中元素的属性,但不能检索元素本身

可以在Ruby中检索哈希中元素的属性,但不能检索元素本身,ruby,performance,hash,Ruby,Performance,Hash,在下面的代码中,我在从散列节点\u散列检索元素时遇到了巨大的问题。散列包含根据可用数据构建的系统发育树的节点。每个节点都有一个唯一的ID,它是散列的密钥。当我试图访问散列的一个元素时,例如node_hash[10],Ruby只是旋转轮子,无法检索它。但是,如果执行类似于node_hash[10]的操作,则返回名称。我知道正建立适当的关系,因为我可以做类似的事情 node_hash[1].children.each do |child| puts child.name end 我得到了 ro

在下面的代码中,我在从散列节点\u散列检索元素时遇到了巨大的问题。散列包含根据可用数据构建的系统发育树的节点。每个节点都有一个唯一的ID,它是散列的密钥。当我试图访问散列的一个元素时,例如node_hash[10],Ruby只是旋转轮子,无法检索它。但是,如果执行类似于node_hash[10]的操作,则返回名称。我知道正建立适当的关系,因为我可以做类似的事情

node_hash[1].children.each do |child|
  puts child.name
end
我得到了

root
Viruses
Viroids
unclassified sequences
other sequences
cellular organisms
但它只是在打印完所有这些之后等待。这是完整的代码

class Node
  attr_accessor :name, :kind, :children, :parent
  def initialize(name=nil, kind=nil, children=nil, parent=nil)
    @name   = name
    @kind   = kind
    @parent = parent
    if children
      @children = children
    else
      @children = []
    end
  end
  def add_child(child)
    @children << child
  end
end

node_hash = {}

File.open("taxdump/names.dmp", "r") do |name_file|
  name_file.each_line do |line|
    split_line = line.split("|")
    if split_line[3].include? 'scientific name'
      id_num = Integer(split_line[0])
      name   = split_line[1].strip
      node_hash[id_num] = Node.new(name)
    end
  end
end

File.open("taxdump/nodes.dmp", "r") do |node_file|
  node_file.each_line do |line|
    split_line = line.split("|")
    id_num = Integer(split_line[0].strip)
    par_id = Integer(split_line[1].strip)]
    child  = node_hash[id_num]
    parent = node_hash[par_id]
    child.parent = parent
    child.kind   = split_line[2].strip
    parent.add_child(child)
  end
end
编辑:我只是让其中一个节点加载,大约一分钟后,看起来像整个树结构的内容被打印出来。Ruby似乎在递归地遍历树,显示节点的父节点及其子节点,然后是父节点的父节点及其子节点,等等。我将尝试覆盖inspect。希望这能奏效


编辑2:这就成功了。

所以我只加载了一个节点,大约一分钟后,看起来树的整个结构都打印出来了。Ruby递归地遍历树,显示节点的父节点及其子节点,然后是父节点的父节点及其子节点,等等。生成字符串花费了很长时间。覆盖“检查”以更改每个节点的显示方式修复了此问题。

向我们显示您遇到问题的数据示例。抱歉?没有我遇到麻烦的数据样本。这一切都被读取到node_散列中,非常好。问题是从散列中检索元素。如果我尝试访问散列中的某个元素,例如a=node\u hash[10],则需要花费很长时间。很抱歉,应该是node\u hash[1]。children。固定的