gpt4 book ai didi

ruby - 如何检测哈希中的重复键并为重复项添加前缀?

转载 作者:太空宇宙 更新时间:2023-11-03 17:42:39 24 4
gpt4 key购买 nike

我有两个数组,我在 Ruby 中使用哈希创建一个键值对。将两个数组压缩成键值对并在重复项的键名前添加前缀(如“A-”)时,如何检测重复键?

我正在使用 .zip 合并两个数组并使一个成为键,另一个成为值

[0] = "David"
[1] = "John"
[2] = "Alex"
[3] = "Sam"
[4] = "Caleb"
[5] = "David"
[6] = "John"
[7] = "Alex"
[8] = "Sam"

[0] = "1"
[1] = "2"
[2] = "3"
[3] = "4"
[4] = "5"
[5] = "6"
[6] = "7"
[7] = "8"
[8] = "9"


name_number_key_value_pair_hash = first_names.zip(numbers).to_h
puts(name_number_key_value_pair_hash)

预期:{“大卫”=>“1”,“约翰”=>“2”,“亚历克斯”=>“3”,“山姆”=>“4”,“迦勒”=>“5”,“A-David"=>"6", "A-John"=>"7", "A-Alex"=>"8", "A-Sam"=>"9"实际的:{“大卫”=>“6”,“约翰”=>“7”,“亚历克斯”=>“8”,“山姆”=>“9”,“迦勒”=>“5”

最佳答案

看起来很直接附上代码片段

names = %w[David John Alex Sam Caleb David John Alex Sam]
numbers = %w[1 2 3 4 5 6 7 8 9]

key_pair = {}
names.each_with_index do |name, index|
name = "A-#{name}" if key_pair[name]
key_pair[name] = numbers[index]
end

它生成预期的输出:

{"David"=>"1", "John"=>"2", "Alex"=>"3", "Sam"=>"4", "Caleb"=>"5", "A-David"=>"6", "A-John"=>"7", "A-Alex"=>"8", "A-Sam"=>"9"}

关于ruby - 如何检测哈希中的重复键并为重复项添加前缀?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54696941/

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