我有以下代码,它工作正常。
months = {"Feb"=>["day1", "day2"]}
i = 0
while i < 5 do
months["Feb"][i] = "day#{i}"
i += 1
end
puts months
$&GT; {“Feb”=&gt; [“day0”,“day1”,“day2”,“day3”,“day4”]}
但是,如果我删除第一行我初始化哈希值或尝试在运行中向不同的哈希键添加值时,我会收到一个未定义的'月'错误。
所以我很困惑。 Ruby会不允许您随意添加密钥到哈希?我习惯了Perl,你可以随便开始制作哈希和数组。但我知道Perl会对哈希和哈希进行处理。数组作为单独的对象,因为Ruby的一切都被认为是相同的,所以我不知道它是否与它有关(尽管Perl方式可能是“马虎”^ _ ^)
答案 0 :(得分:1)
在Ruby中,您必须在使用它之前初始化变量(看起来像一个合理的策略......)。另请注意,您所写的不是惯用的Ruby,另一种选择:
months = {"Feb" => 0.upto(4).map { |i| "day#{i}" }}
更新:
months["Feb"] = 0.upto(4).map { |i| "day#{i}" }
答案 1 :(得分:1)
您总是需要在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"]}
一些有用的文档:
答案 2 :(得分:0)
# the ||= set this to an empty hash({}) if it hasn't been initialized yet
months ||= {}
#updated as you like, use symbols :feb over string "feb" as the key (read this in other questions in this website)
months[:feb] = (0..4).map {|n| "day#{n}"}
p months #==> {:feb=>["day0", "day1", "day2", "day3", "day4"]}
答案 3 :(得分:0)
基于你们所说的我搞砸了,看起来Ruby希望密钥存在,然后才能开始为该密钥分配值。
hashname = Hash.new
hashname[:foo] = {}
hashname[:foo][3] = "test"
hashname[:foo][1] = "test1"
hashname[:bar] = {}
hashname[:bar][3] = "test3"
puts hashname
puts hashname[:foo][1]
C:\Ruby>scratch.rb
{:foo=>{3=>"test", 1=>"test1"}, :bar=>{3=>"test3"}}
test1
密钥存在后,您可以根据需要开始分配值。虽然在这种情况下你可以看到我正在创建一个散列哈希&#34;而不是&#34;数组的散列&#34;因为.map方法确实让我无法理解为什么。
感谢您的帮助!