我正在尝试将不同的值添加到数组中,以将相同的键添加到哈希中。我的函数没有在数组中创建新实例,而是求和了数组元素的索引值
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] }
答案 0 :(得分:3)
只需进行两个小修改,代码就可以工作。
hash = Hash.new([])
更改为hash = Hash.new { |h,k| h[k] = [] }
您实际上不应该使用Hash.new([])
,有关说明,请参见此文章:https://mensfeld.pl/2016/09/ruby-hash-default-value-be-cautious-when-you-use-it/
hash[ele] = (idx)
更改为hash[ele].push(idx)
您不想在遇到新索引时替换该值,而是想将其推入数组。
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]}