ruby哈希与mp3目录中的文件列表

时间:2012-02-03 10:23:22

标签: ruby

我有数千个这样命名的mp3:record-20091030.mp3record-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     

2 个答案:

答案 0 :(得分:2)

你在循环的每次迭代中都覆盖了存储的值(Hash.newArray.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"}}