Forum: Ruby A Hash 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.
Af3cecc8af253b5acd3c09c5b67c0074?d=identicon&s=25 Valentino Lun (on9west)
on 2009-01-15 09:24
Dear all

I want to build a hash which store the values from database, but failed.
Please give me some hints please. Thank you.

services table
h_code       s_code       status
AHN          BBS          3
AHN          MBS          1
AHN          HMS          1
CMC          CRS          1
CMC          CPS          1
CMC          BTNS         1
GH           CRS          1
GH           CPS          1


My expectation
all = {"AHN" => {"BBS" => 3, "MBS" => 1, "HMS" => 1}
       "CMC" => {"CRS" => 1, "CPS" => 1, "BTNS" => 1}
       "GH" => {"CRS" = 1, "CPS" => 1}
      }


all = {}
Service.find(:all).each do |s|
   # How to do here?
   # I try all[s.h_code][s.s_code]=s.status, but not work
end

Thank you very much

Valentino
5772c599ccab3081e0fffb1d54f3b6de?d=identicon&s=25 Andrew Timberlake (andrewtimberlake)
on 2009-01-15 10:01
(Received via mailing list)
On Thu, Jan 15, 2009 at 10:23 AM, Valentino Lun <sumwo@yahoo.com> wrote:

> CMC          CRS          1
>      }
> Valentino
> --
> Posted via http://www.ruby-forum.com/.
>
>
Try the following:

#Create a new hash where every key has a default entry of an empty hash
(hash of hashes)
all = Hash.new{|h,k| h[k] = {}}
Service.find(:all).each do |s|

end
h_code       s_code       status

--
Andrew Timberlake
http://ramblingsonrails.com
http://www.linkedin.com/in/andrewtimberlake

"I have never let my schooling interfere with my education" - Mark Twain
5772c599ccab3081e0fffb1d54f3b6de?d=identicon&s=25 Andrew Timberlake (andrewtimberlake)
on 2009-01-15 10:03
(Received via mailing list)
On Thu, Jan 15, 2009 at 10:23 AM, Valentino Lun <sumwo@yahoo.com> wrote:

> CMC          CRS          1
>      }
> Valentino
> --
> Posted via http://www.ruby-forum.com/.
>
>
Sorry about the previous post - I clicked ENTER too soon

Try the following:

#Create a new hash where every key has a default entry of an empty hash
# (hash of hashes)
all = Hash.new{|h,k| h[k] = {}}

Service.find(:all).each do |s|
   all[s.h_code][s.s_code] = status
end

--
Andrew Timberlake
http://ramblingsonrails.com
http://www.linkedin.com/in/andrewtimberlake

"I have never let my schooling interfere with my education" - Mark Twain
This topic is locked and can not be replied to.