开发者

How can I access the hashes in an array of hashes?

I have an array of hashes titled entities

Here is a look at the array:

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

Output:

"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
"entit开发者_如何学编程ies[0]"
--- "-"
"entities[1]"
--- "-"
"entities[2]"
--- "-"

I can't figure out how to access the individual hashes. Should something be coming up when I do p entities[0]?


Is entities.kind_of? String true? It looks like entities is actually a YAML string. Hence, entities[0/1/2] are the first three dashes of the YAML.


Did that copy right? the output, pasted into a irb session comes out as a single string, not an array:

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" 


Your entitles may be not really array of hashes. Look this:

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}]

Try entitles.class and entitles[0].class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜