您总是需要在 Ruby 中初始化变量。但是您可以按如下方式初始化哈希:
# Using {} to creates an empty hash
months = {}
# or create a new empty hash object from Hash class
months = Hash.new
# instead of
months = {"Feb"=>["day1", "day2"]}
在哈希中初始化一个数组:
# Array.new creates a new Array with size 5
# And values within Hash.new block are the default values for the hash
# i.e. When you call the Hash#[], it creates a new array of size 5
months = Hash.new { |hash, key| hash[key] = Array.new(5) }
puts months #=> {}
puts months["Feb"] # Here the Hash creates a new Array inside "Feb" key
puts months #=> {"Feb" => [nil, nil, nil, nil, nil]}
puts months["Feb"][3] = "Day3"
puts months #=> {"Feb" => [nil, nil, nil, "Day3", nil]}
要使用未定义的数组大小执行相同操作:
months = Hash.new { |hash, key| hash[key] = [] }
puts months #=> {}
months["Feb"].push "Day0"
puts months #=> {"Feb" => ["Day0"]}
months["Feb"].push "Day1"
puts months #=> {"Feb" => ["Day0", "Day1"]}
我认为更优雅的方法是使用 map 方法在将其绑定到“Feb”键之前构建您的天数:
months = {"Feb" => (0..4).map{ |i| "day#{i}" }}
# => {"Feb"=>["day0", "day1", "day2", "day3", "day4"]}
如果您不想输入月份名称,则可以要求 Date 类并通过 Fixnum 获取月份名称:
require 'date'
months = {Date::ABBR_MONTHNAMES[2] => (0..4).map{ |i| "day#{i}"}}
# => {"Feb"=>["day0", "day1", "day2", "day3", "day4"]}
要为所有月份生成相同的结构,您可以执行以下操作:
days = (0..4).map{ |d| "day#{d}"}
months = (1..12).map{ |m| {Date::ABBR_MONTHNAMES[m] => days }}
# => {"Jan"=>["day0", "day1", "day2", "day3", "day4"],
# "Feb"=>["day0", "day1", "day2", "day3", "day4"],
# ...
# "Dec"=>["day0", "day1", "day2", "day3", "day4"]}
一些有用的文档: