簡體   English   中英

Ruby:放置變量的值和名稱

[英]Ruby: puts a variable's value and name

我有一個數組散列的散列:

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個變量對應我的hash的3代:author為第一代變量,等於一個hash; 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.

我可以做一些事情,比如在哈希中推送一個值,讓它成為一個鍵嗎?

如果沒有,我怎么能有一些東西會給我這個結果:

代碼:

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

而不是在此處將值設置為字符串:

hash[author][file] = file

您可以將字符串設置為鍵的值:

hash[author][file][:file] = file

然后讓數組成為另一個屬性

hash[author][file][:times] ||= []
hash[author][file][:times].push time

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM