Forum: Ruby Hash of Arrays nItems problem

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.
unknown (Guest)
on 2006-03-18 00:15
(Received via mailing list)
I'm having a bit of problem using a hash of arrays.  It appears that
nitems are wrong for the individual elements are wrong when I do this:

#!/usr/bin/env ruby
$:.unshift(File.join('..', 'lib'))
require 'http-access2'

h = HTTPAccess2::Client.new()
element = Hash.new([])

while urlstr = ARGV.shift
  response = h.get(urlstr) { |data|

data.gsub(/<(description|title|link)>(.+)<\/(description|title|link)>/)
{
      print $1,"\n"
      element[$1].push($2.gsub(/\s\s+/m," "))
    }
  }
end

print "site description ---> ", site_description, "\n"
print "site title ---------> ", site_title, "\n"
print "description.nitems -> ", element['description'].nitems, "\n"
print "title.nitems -------> ", element['title'].nitems, "\n"

site_description = element['description'].shift
site_title = element['title'].shift

while element['description'].nitems > 0
  print element['title'].shift.gsub(/\n+/, ""),"\n"
  print element['description'].shift.gsub(/\n+/, ""),"\n\n"
end

% ruby rss.rb http://involution.com/rss.php
site description ---> involution.com
site title ---------> http://involution.com
description.nitems -> 30
title.nitems -------> 30

There are 10 of each links, putting a print in the hget enclosure shows
that only 10 descriptions, links, and titles are added, but the
individual array sizes are reported as 30.  What am I doing wrong?

Tony
Robert K. (Guest)
on 2006-03-19 14:34
(Received via mailing list)
removed_email_address@domain.invalid wrote:
> I'm having a bit of problem using a hash of arrays.  It appears that
> nitems are wrong for the individual elements are wrong when I do this:
>
> #!/usr/bin/env ruby
> $:.unshift(File.join('..', 'lib'))
> require 'http-access2'
>
> h = HTTPAccess2::Client.new()
> element = Hash.new([])

You want

element = Hash.new {|h,k| h[k] = []}

Otherwise you'll be adding to the *same* single array instance for *all*
elements.

Kind regards

    robert
unknown (Guest)
on 2006-03-20 00:58
(Received via mailing list)
Oh, snap.  Thanks robert.  I will name my first son Robert in your
honor.  Thanks a million.

Tony P.
http://involution.com
Robert K. (Guest)
on 2006-03-20 11:43
(Received via mailing list)
removed_email_address@domain.invalid wrote:
> Oh, snap.  Thanks robert.  I will name my first son Robert in your
> honor.  Thanks a million.

You're welcome.  And I feel humbled.

Kind regards

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