如何在哈希数组中访问哈希?

时间:2011-03-10 03:33:17

标签: ruby yaml

我有一系列标题为entities

的哈希值

以下是数组:

  p "entities"
  y entities
  p "entities[0]"
  y entities[0]
  p "entities[1]"
  y entities[1]
  p "entities[2]"
  y entities[2]

输出:

"entities"
--- |
 --- 
 - :text: Berlin
   :links: 
   - http://dbpedia.org/resource/Berlin
 - :text: Jan Karski
   :links: 
   - http://dbpedia.org/resource/Jan_Karski
 - :text: God
   :links: 
   - http://dbpedia.org/resource/God
"entities[0]"
--- "-"
"entities[1]"
--- "-"
"entities[2]"
--- "-"

我无法弄清楚如何访问各个哈希值。当我p entities[0]时会出现什么事情?

3 个答案:

答案 0 :(得分:3)

entities.kind_of? String是真的吗?看起来实体实际上是一个YAML字符串。因此,实体[0/1/2]是YAML的前三个破折号。

答案 1 :(得分:1)

那个副本没错吗?粘贴到irb会话中的输出以单个字符串形式出现,而不是数组:

ruby-1.9.2-p0 > YAML::parse("--- |
ruby-1.9.2-p0">  --- 
ruby-1.9.2-p0">  - :text: Berlin
ruby-1.9.2-p0">    :links: 
ruby-1.9.2-p0">    - http://dbpedia.org/resource/Berlin
ruby-1.9.2-p0">  - :text: Jan Karski
ruby-1.9.2-p0">    :links: 
ruby-1.9.2-p0">    - http://dbpedia.org/resource/Jan_Karski
ruby-1.9.2-p0">  - :text: God
ruby-1.9.2-p0">    :links: 
ruby-1.9.2-p0">    - http://dbpedia.org/resource/God
ruby-1.9.2-p0"> ").value
 => "--- \n- :text: Berlin\n  :links: \n  - http://dbpedia.org/resource/Berlin\n- :text: Jan Karski\n  :links: \n  - http://dbpedia.org/resource/Jan_Karski\n- :text: God\n  :links: \n  - http://dbpedia.org/resource/God\n" 

答案 2 :(得分:1)

你的entitles可能不是真正的哈希数组。 看这个:

irb(main):001:0> e = [{:a=>1,:b=>2},{:c=>3,:d=>4}]
irb(main):002:0> p e
[{:a=>1, :b=>2}, {:c=>3, :d=>4}]

尝试entitles.classentitles[0].class