Forum: Ruby Adding to Hashes

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.
Cd58ba31277139562fa17cd36c5fc789?d=identicon&s=25 Nick Black (Guest)
on 2007-02-02 11:57
(Received via mailing list)
Hello,

I need to add key and value pairs to a hash dynamically.  I want to do
this:

  array = []
  array << "hello"
  array << "world"

But with k v pairs of a hash.  The hash is being populated from a
database and there is a potenitally unlimited (though realistically
limited to less than 20) number of differnet keys, which my program
will not know about until it talks to the database.

Can I dynamically create a hash something like this:

dbh.query("select k, v from foo where id = #{id}").each_hash do |kv|

       k = kv['k']
       v = kv['v']

       myhash << k,v
end

return myhash



Thanks for the help!
97550977337c9f0a0e1a9553e55bfaa0?d=identicon&s=25 Jan Svitok (Guest)
on 2007-02-02 12:05
(Received via mailing list)
On 2/2/07, Nick Black <nickblack1@gmail.com> wrote:
> limited to less than 20) number of differnet keys, which my program
> will not know about until it talks to the database.
>
> Can I dynamically create a hash something like this:
>
> dbh.query("select k, v from foo where id = #{id}").each_hash do |kv|
>
>        k = kv['k']
>        v = kv['v']
>
>        myhash << k,v

Why not just
   myhash[k] = v
Cd58ba31277139562fa17cd36c5fc789?d=identicon&s=25 Nick Black (Guest)
on 2007-02-02 16:36
(Received via mailing list)
Figured it out - its simple as always:

yourhash['key'] = value

adds to the hash (just like the book says)
This topic is locked and can not be replied to.