Forum: Ruby Array of Hashes (created by xmlsimple)

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
6c2401c27c799402ffc6d1c1a94a675d?d=identicon&s=25 Maui Guide (newtoruby)
on 2009-04-17 11:47
I'm relatively new and this had me thoroughly confused today.

require 'xmlsimple'

myxml = "<a href=\"http://www.mysite.com/category/file.php\">\r\n<img...
src=\"http://www.mysite.com/images/picture.jpg\" width=\"640\"
height=\"480\" alt=\"\" border=\"0\"/></a>"

xmltags = XmlSimple.xml_in(myxml)

href_tag = xmltags['href']             #<-- this works fine
img_tag  = xmltags['img']              #<-- this works fine
img_src  = xmltags['img']['src']       #<-- this doesn't work

irb(main):221:0> p img_tag
[{"src"=>"http://www.mysite.com/images/picture.jpg",
"border"=>"0", "height"=>"480", "alt"=>"", "width"=>"640"}]

I can loop through all the hashes in the array (via img_tag.each do |t|)
But isn't there a way to access the img src attribute directly?

Thanks!
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-04-17 15:26
(Received via mailing list)
2009/4/17 Maui Guide <mauiguide@gmail.com>:
> href_tag = xmltags['href']             #<-- this works fine
> img_tag  = xmltags['img']              #<-- this works fine

Actually I believe the namings of your variables to be misleading:
there should be an "s" at the end because what you get are multiple
elements. Which is also the explanation why

> img_src  = xmltags['img']['src']       #<-- this doesn't work

Also, it seems there is no point in traversing the XML document again
to get the same "img" tags again.

> irb(main):221:0> p img_tag
> [{"src"=>"http://www.mysite.com/images/picture.jpg",
> "border"=>"0", "height"=>"480", "alt"=>"", "width"=>"640"}]
>
> I can loop through all the hashes in the array (via img_tag.each do |t|)
> But isn't there a way to access the img src attribute directly?

You need to decide whether you expect one or many tags. If you are
interested in one only and if it is guaranteed that there is exactly
one present you can do

href_tag = xmltags['href'].first
img_tag  = xmltags['img'].first
img_src  = img_tag['src']       #<-- this should work

Cheers

robert
This topic is locked and can not be replied to.