我有散列哈希顯示爲樹,就像路線。下面,我添加了預期結果和我得到的結果的示例。如何做紅寶石遞歸
例哈希:
hash = {
'movies' => {
'action' => {
'2007' => ['video1.avi', 'x.wmv'],
'2008' => ['']
},
'comedy' => {
'2007' => [],
'2008' => ['y.avi']
}
},
'audio' => {
'rock' => {
'2003' => [],
'2004' => ['group', 'group1']
}
}
}
我希望這樣的結果:
movies
movies\action
movies\action\2007
movies\action\2007\video1.avi
movies\action\2007\x.wmv
movies\action\2008
movies\comedy\2007
movies\comedy\2008
movies\comedy\2008\y.avi
audio
audio\rock\2003
audio\rock\2004
audio\rock\2004\group
audio\rock\2004\group1
下面是一些代碼,我提出:
def meth(key, val)
val.each do |key1, val1|
puts "#{key}/#{key1}"
meth(key1, val1) if val1
end
end
hash.each do |key, val|
puts key
meth(key,val)
end
它返回這樣的結果:
movies
movies/action
action/2007
2007/video1.avi
2007/x.wmv
action/2008
2008/
movies/comedy
comedy/2007
comedy/2008
2008/y.avi
audio
audio/rock
rock/2003
rock/2004
2004/group
2004/group1
任何人都可以解釋如何做到這一點?
UPDATE
感謝答案。在這種情況下,我想出了使用這個代碼。提示是將key1
設置爲以前的結果。
def meth key, val
val.each do |key1, val1|
puts "#{key}/#{key1}"
key1 = "#{key}/#{key1}"
meth(key1, val1) if val1
end
end
我想這一點,但產量並不好 –