Adding to Hashes

N

Nick Black

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!
 
J

Jan Svitok

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
 
N

Nick Black

Figured it out - its simple as always:

yourhash['key'] = value

adds to the hash (just like the book says)



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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,230
Messages
2,571,161
Members
47,794
Latest member
LucretiaEl

Latest Threads

Top