我有一个哈希的数组哈希:
hash = Hash.new do |hash, key|
hash[key] = Hash.new do |hash, key|
hash[key] = Array.new
end
end
我还有一个获取3个变量值的循环:
author = gets.chomp
file = gets.chomp
time = Time.now
这三个变量对应于我的哈希的3代:作者是第一代变量,并且等于哈希; file是第二代变量,等于数组; time是第三代变量,等于简单值。
这就是我打算将值分配给哈希的方法:
hash[author][file] = file
hash[author][file].push(time)
我的问题是,当我想在哈希中实现一个作者和一个文件时,我认为我会破坏第二代哈希或数组并将变量设置为等于简单值:
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.
我可以做一些像在哈希中推送一个值的东西,这样它就变成了一个键吗?
如果没有,我怎么能得到能够给我这个结果的东西:
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
结果:
1
a1
un
uno
a2
uunn
uunnoo
2
b1
deux
dos
b2
ddeuxx
ddooss
答案 0 :(得分:1)
而不是在这里将值设置为字符串:
hash[author][file] = file
您可以将字符串设置为键的值:
hash[author][file][:file] = file
然后让数组成为另一个属性
hash[author][file][:times] ||= []
hash[author][file][:times].push time