Forum: Ruby Hash and Arrays...

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.
6b2144362fffd4f71cca755d4045846f?d=identicon&s=25 Josselin (Guest)
on 2007-04-24 12:46
(Received via mailing list)
I receive from yahoo weather an Hash like this one,

response
=> {"xmlns:geo"=>"http://www.w3.org/2003/01/geo/wgs84_pos#",
"xmlns:yweather"=>"http://xml.weather.yahoo.com/ns/rss/1.0",
"version"=>"2.0", "channel"=>[{"title"=>["Yahoo! Weather - Error"],
"description"=>["Yahoo! Weather Error"], "item"=>[{"title"=>["City not
found"], "description"=>["\n Sorry, your location 'dfghh' was not
found. Please try again.\n "]}]}]}

I need to test the response for an error on channel title,  I wrote :

(response.fetch("channel")[0]).fetch("title")[0]
=> "Yahoo! Weather - Error"

to get the string, but is there any simpler way to do it ?  I'm not yet
very easy with Hash...

thanks
753dcb78b3a3651127665da4bed3c782?d=identicon&s=25 Brian Candler (Guest)
on 2007-04-24 13:18
(Received via mailing list)
On Tue, Apr 24, 2007 at 07:45:04PM +0900, Josselin wrote:
> I need to test the response for an error on channel title,  I wrote :
>
> (response.fetch("channel")[0]).fetch("title")[0]
> => "Yahoo! Weather - Error"
>
> to get the string, but is there any simpler way to do it ?

response["channel"][0]["title"][0]

or:

response["channel"].first["title"].first

But it also depends on how you are parsing the XML. If you're using
xmlsimple then you can pass option 'ForceArray' => false, which gets rid
of
the arrays. Then you can do

response["channel"]["title"]
6b2144362fffd4f71cca755d4045846f?d=identicon&s=25 Josselin (Guest)
on 2007-04-25 09:50
(Received via mailing list)
On 2007-04-24 13:17:37 +0200, Brian Candler <B.Candler@pobox.com> said:

>>
>
> response["channel"].first["title"].first
>
> But it also depends on how you are parsing the XML. If you're using
> xmlsimple then you can pass option 'ForceArray' => false, which gets rid of
> the arrays. Then you can do
>
> response["channel"]["title"]

thanks a lot Brian, that's exactly what I am using... so .. simple !

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