gpt4 book ai didi

ruby - 从两个不同大小的数组创建一个 Hash 并迭代直到没有一个键为空

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

有两个不同大小的数组,我想将较长 数组作为键,将较短 数组作为值。但是,我不希望任何键保持为空,因此我需要继续迭代 shorter 数组,直到所有键都有一个值。

编辑: 我想保持数组更长时间完整,但没有空值,这意味着继续迭代更短,直到所有键都有一个值。

longer  = [1, 2, 3, 4, 5, 6, 7]
shorter = ['a', 'b', 'c']

Hash[longer.zip(shorter)]
#=> {1=>"a", 2=>"b", 3=>"c", 4=>nil, 5=>nil, 6=>nil, 7=>nil}

预期结果

#=> {1=>"a", 2=>"b", 3=>"c", 4=>"a", 5=>"b", 6=>"c", 7=>"a"}

最佳答案

这是一个优雅的。您可以“循环”短数组

longer  = [1, 2, 3, 4, 5, 6, 7]
shorter = ['a', 'b', 'c']

longer.zip(shorter.cycle).to_h # => {1=>"a", 2=>"b", 3=>"c", 4=>"a", 5=>"b", 6=>"c", 7=>"a"}

关于ruby - 从两个不同大小的数组创建一个 Hash 并迭代直到没有一个键为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40156737/

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