我有数千个这样命名的mp3:record-20091030.mp3
,record-20091130.mp3
等
我想解析并获取ruby哈希year->month->[days] (hash, hash, array)
这段代码有什么问题?
#!/usr/bin/env ruby
files = Dir.glob("mp3/*.mp3")
@result = Hash.new
files.each do |file|
date = file.match(/\d{8}/).to_s
year = date[0,4]
month = date[4,2]
day = date[6,2]
@result[year.to_i] = Hash.new
@result[year.to_i][month.to_i] = Array.new
@result[year.to_i][month.to_i] << day
end
puts @result
答案 0 :(得分:2)
你在循环的每次迭代中都覆盖了存储的值(Hash.new
和Array.new
),如果散列/数组是nil,你应该只这样做,例如:
@result[year.to_i] ||= Hash.new
@result[year.to_i][month.to_i] ||= Array.new
答案 1 :(得分:0)
我试图做一些修复。
#!/usr/bin/env ruby
files = Dir.glob("mp3/*.mp3")
@result = Hash.new{|h,k| h[k]=Hash.new(&h.default_proc) }
files.each do |file|
date = file[-12..-4]
year, month, day = date.scan(/(.{4})(.{2})(.{2})/).first.map(&:to_i)
@result[year][month][day] = file
end
@result.each_pair { |name, val| puts "#{name} #{val}" }
# => 2009 {10=>{30=>"mp3/record-20091030.mp3"},
# 11=>{30=>"mp3/record-20091130.mp3"}}
# 2010 {1=>{23=>"mp3/record-20100123.mp3"}}