Reputation: 703
I have a hash of hashes of arrays:
hash = Hash.new do |hash, key|
hash[key] = Hash.new do |hash, key|
hash[key] = Array.new
end
end
I also have a loop that gets the values of 3 variables:
author = gets.chomp
file = gets.chomp
time = Time.now
These 3 variables correspond to the 3 generations of my hash: author is the first generation variable, and is equal to a hash; file is the second generation variable, and is equal to an array; time is the third generation variable, and is equal to a simple value.
This is how I intended to assign the values to the hash:
hash[author][file] = file
hash[author][file].push(time)
My problem is that when I want to implement an author and a file in the hash, I think that I destroy the second generation hash or the array and set the variable equal to a simple value instead:
hash[author][file] = file #here, instead of adding a new key in the 2nd generation hash, I replace the hash with a single value.
hash[author][file].push(time) #the "file" variable isn't an array anymore, it is a string, so I can't push anything in it.
Can I do something like pushing a value in a hash, so it becomes a key?
If not, how can I have something that would give me this result:
CODE:
hash = {1 => {"a1" => ["un", "uno"], "a2" => ["uunn", "uunnoo"]}, 2 => {"b1" => ["deux", "dos"], "b2" => ["ddeuxx", "ddooss"]}}
hash.each do |key, value|
puts key
value.each do |key, value|
puts key
value.each do |value|
puts value
end
end
end
RESULT:
1
a1
un
uno
a2
uunn
uunnoo
2
b1
deux
dos
b2
ddeuxx
ddooss
Upvotes: 1
Views: 581
Reputation: 26778
Rather then setting the value to a string here:
hash[author][file] = file
You can set the string as a value of a key:
hash[author][file][:file] = file
And then let the array be another property
hash[author][file][:times] ||= []
hash[author][file][:times].push time
Upvotes: 1