gpt4 book ai didi

Ruby:将不同的数组值添加到同一键的散列中

转载 作者:数据小太阳 更新时间:2023-10-29 08:42:25 25 4
gpt4 key购买 nike

我正在尝试将不同的值添加到数组中,以将相同的键添加到散列中。我的函数不是在数组中创建一个新实例,而是对数组元素的索引值求和

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] }

最佳答案

通过两个小的修改,您的代码将正常工作。

  1. 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/

  1. 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]}

关于Ruby:将不同的数组值添加到同一键的散列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56622848/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com