ruby使用数组值添加到哈希
我尝试了下面的ruby代码,我认为它会将单词长度的散列返回到具有这些长度的单词。相反,它是空的ruby使用数组值添加到哈希,ruby,hash,Ruby,Hash,我尝试了下面的ruby代码,我认为它会将单词长度的散列返回到具有这些长度的单词。相反,它是空的 map = Hash.new(Array.new) strings = ["abc","def","four","five"] strings.each do |word| map[word.length] << word end map=Hash.new(Array.new) 字符串=[“abc”、“def”、“四”、“五”] 字符串。每个do |字| map[w
map = Hash.new(Array.new)
strings = ["abc","def","four","five"]
strings.each do |word|
map[word.length] << word
end
map=Hash.new(Array.new)
字符串=[“abc”、“def”、“四”、“五”]
字符串。每个do |字|
map[word.length]我认为第一个版本的真正含义是默认值只有一个数组。第二个示例显式创建了一个新数组(如果还不存在)
这看起来是一个很好的进一步阅读 问题在于,您实际上没有为哈希键分配任何内容,您只是在使用所有这些,请检查:
这很奇怪。对于第一个示例,如果您执行map=Hash.new{{h,k{h[k]=[]}
谢谢。我还在学习ruby,所以学习习语很有帮助。帮了我很多,谢谢!然而,这对我来说不起作用,直到我将+=
之后的单词更改为数组,如[word]
map = Hash.new
strings = ["abc","def","four","five"]
strings.each do |word|
map[word.length] ||= []
map[word.length] << word
end
h = Hash.new []
p h[0] # []
h[0] << "Hello"
p h # {}
p h[0] # ["Hello"]
p h[1] # ["Hello"]
map = Hash.new []
strings = ["abc", "def", "four", "five"]
strings.each do |word|
map[word.length] += [word]
end
["abc", "def", "four", "five"].group_by(&:length)
#=> {3=>["abc", "def"], 4=>["four", "five"]}