[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Adding to Hashes

Nick Black

2/2/2007 10:56:00 AM

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!

2 Answers

Jano Svitok

2/2/2007 11:05:00 AM

0

On 2/2/07, Nick Black <nickblack1@gmail.com> wrote:
> 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

Why not just
myhash[k] = v

> end
>
> return myhash

Nick Black

2/2/2007 3:36:00 PM

0

Figured it out - its simple as always:

yourhash['key'] = value

adds to the hash (just like the book says)



On 2/2/07, Nick Black <nickblack1@gmail.com> wrote:
> 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!
>
>


--
Nick Black
--------------------------------
http://www.black...