Ruby:为同一个键向哈希中添加不同的数组值
我试图将同一个键的不同值添加到一个数组中。我的函数不是在数组中创建新实例,而是汇总数组元素的索引值Ruby:为同一个键向哈希中添加不同的数组值,ruby,Ruby,我试图将同一个键的不同值添加到一个数组中。我的函数不是在数组中创建新实例,而是汇总数组元素的索引值 def dupe_indices(array) hash = Hash.new([]) array.each.with_index { |ele, idx| hash[ele] = (idx) } hash end 我明白了 print dupe_indices(['a', 'b', 'c', 'a', 'c']) => {"a"=>3, "b"=>1,
def dupe_indices(array)
hash = Hash.new([])
array.each.with_index { |ele, idx| hash[ele] = (idx) }
hash
end
我明白了
print dupe_indices(['a', 'b', 'c', 'a', 'c']) => {"a"=>3, "b"=>1,
"c"=>4}
预期产量
print dupe_indices(['a', 'b', 'c', 'a', 'c']) => { 'a' => [0, 3], 'b'
=> [1], 'c' => [2, 4] }
只要稍加修改,你的代码就可以工作了
hash=hash.new([])
更改为hash=hash.new{h,k{h[k]=[]}
hash[ele]=(idx)
更改为hash[ele]。推送(idx)
非常感谢你!我对这一行有点困惑:hash=hash.new{h,k{h[k]=[]},特别是带有'h'参数。h和k代表hash和key。当在散列中查找未知密钥时,将调用此块。你可以在谷歌上搜索“ruby默认哈希块”以获得更多解释,现在就开始吧!谢谢Timur,
每个带索引的通常都是每个带索引的编写的,除非希望索引的基数不是零(例如,…每个带索引的(1)…
)。在这里定义散列实际上与hash={}相同;除非hash.key?(ele);hash[ele]。push(idx)},否则数组中的每个_的索引{| ele,idx | hash[ele]=[];散列
。最后,您可以通过编写array.each_with_index.with_object(Hash.new{h,k{h[k]=[]){{124;(ele,idx),Hash{Hash[ele],push(idx)}
@TimurShamuradov:“我对这一行有点困惑:Hash=Hash.new{h,k{h[k]=[]),特别是带有'h'参数”–如果您能够准确地描述关于Hash::new
的文档中您不清楚的内容,这将非常有帮助。这样,Ruby开发人员就可以改进文档,使未来的开发人员不会遇到与您相同的问题。帮助让世界变得更美好!或者ari.each_index.group_by{i|ari[i]}
array = ['a', 'b', 'c', 'a', 'c']
def dupe_indices(array)
hash = Hash.new { |h,k| h[k] = [] }
array.each.with_index { |ele, idx| hash[ele].push(idx) }
hash
end
dupe_indices(array)
# => {"a"=>[0, 3], "b"=>[1], "c"=>[2, 4]}