Hi all,
I decided to take a deep look into hashes today and how hashes of arrays
are handled. This is a bit of a grasp for me because most of the
languages I've worked with, arrays are handled in just a few ways. With
Ruby, it's much better.
So, here are my questions using an example scenario I'm creating from
scratch.
Creating a new Hash:
myhash = Hash.new {|h,k| h[k] = {} }
myhash.class
=> Hash
Creating two Arrays:
mykeyarray = Array.[](1,2,3,4,5)
=> [1, 2, 3, 4, 5]
myvaluearray = Array.[](10,20,30,40,50)
=> [10, 20, 30, 40, 50]
5.times do |i|
myhash[mykeyarray[i]][:numbers] = myvaluearray[i]
end
myhash.keys
=> [5, 1, 2, 3, 4]
myhash.values
=> [{:numbers=>50}, {:numbers=>10}, {:numbers=>20}, {:numbers=>30},
{:numbers=>40}]
myhash.inspect
=> "{5=>{:numbers=>50}, 1=>{:numbers=>10}, 2=>{:numbers=>20},
3=>{:numbers=>30}, 4=>{:numbers=>40}}"
So, I would believe that this is a hash of hashes of arrays correct?
Secondly, how would I parse information out of this hash? Creating them
is easy. Extracting exactly the way I want - not so easy.
Let me give you an example:
I create a constant that stores the symbol I want to use for my table.
MY_TABLE_FIELD = [:numbers]
myhash.each do |key|
values = {:compiled_on => Date.today.strftime('%Y-%m-%d')}
MY_TABLE_FIELD.each_with_index do |field, i|
values[field] = key[i]
end
model.create values
end
.. this won't work ..
I want to match the symbol in my hash with the symbol in my constant
(which represents the table field). I want to update the table field
with the value of the hash (10,20,30,40,50). They hash key would
represent the id field (1,2,3,4,5).
How can I accomplish this given the information provided?
···
--
Posted via http://www.ruby-forum.com/.