The nested hash is interpreted as an array

I use a hash to store the little data needed to analyze the website, including the URL, and specific instructions for using Nokogiri to analyze website headers. However, I interpreted the nested Hash as an array.

webSite = {  :everdoH =>  
                        { :url => "http://www.everardoherrera.com/" ,
                          :instruc=> Proc.new PageToParse.css('.contentheading').css('.contentpagetitle')} 
           }

If I do this:

puts webSite.class
webSite.each {|aSite| puts aSite.class }

I get the following:

>> Hash
>> Array

Therefore, I cannot use any of the hash indexing properties.

Any idea why I am not getting a Hash class type on the nested part?

+3
source share
2 answers

Because Hash#each, Hash#each_pairthe key-value of the pair (array) passes as parameters.

webSite = {  :everdoH =>
  { :url => "http://www.everardoherrera.com/" ,
    :instruc=> 'blah'
  }
}
webSite.each { |aSite| p aSite }
# => [:everdoH, {:url=>"http://www.everardoherrera.com/", :instruc=>"blah"}]

Try one of the following (print value class, not key-value pair):

webSite.each {|aSite| puts aSite[1].class }
# => Hash
webSite.each {|key, aSite| puts aSite.class }
# => Hash
webSite.each_value {|aSite| puts aSite.class }
# => Hash
+2
source

Use each_pairto repeat

1.9.3p448 :060 >   webSite.each_pair{|x,y| p y.class}
Hash
 => {:everdoH=>{:url=>"http://www.everardoherrera.com/", :instruc=>"asd"}} 
1.9.3p448 :061 > 
1.9.3p448 :062 >   webSite.each_pair{|x,y| p y}
{:url=>"http://www.everardoherrera.com/", :instruc=>"asd"}
 => {:everdoH=>{:url=>"http://www.everardoherrera.com/", :instruc=>"asd"}} 
1.9.3p448 :063 > 
1.9.3p448 :064 >   webSite.each_pair{|x,y| p x}
:everdoH
 => {:everdoH=>{:url=>"http://www.everardoherrera.com/", :instruc=>"asd"}} 
1.9.3p448 :065 >
0
source

All Articles