gpt4 book ai didi

ruby - 将 Ruby 元组数组转换为给定键数组的散列?

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

我有一个简单的数组

array = ["apple", "orange", "lemon"] 

array2 = [["apple", "good taste", "red"], ["orange", "bad taste", "orange"], ["lemon" , "no taste", "yellow"]]

每当数组中的元素与 array2 中每个元素的第一个元素匹配时,我如何转换为这个散列?

hash = {"apple" => ["apple" ,"good taste", "red"],
"orange" => ["orange", "bad taste", "orange"],
"lemon" => ["lemon" , "no taste", "yellow"] }

我是 ruby​​ 的新手,花了很多钱来做这个操作,但运气不好,有什么帮助吗?

最佳答案

如果键和对之间的映射顺序应该基于array2 中的第一个元素,那么您根本不需要array:

array2 = [
["apple", "good taste", "red"],
["lemon" , "no taste", "yellow"],
["orange", "bad taste", "orange"]
]

map = Hash[ array2.map{ |a| [a.first,a] } ]
p map
#=> {
#=> "apple"=>["apple", "good taste", "red"],
#=> "lemon"=>["lemon", "no taste", "yellow"],
#=> "orange"=>["orange", "bad taste", "orange"]
#=> }

如果你想使用数组来选择元素的子集,那么你可以这样做:

# Use the map created above to find values efficiently
array = %w[orange lemon]
hash = Hash[ array.map{ |val| [val,map[val]] if map.key?(val) }.compact ]
p hash
#=> {
#=> "orange"=>["orange", "bad taste", "orange"],
#=> "lemon"=>["lemon", "no taste", "yellow"]
#=> }

代码 if map.key?(val)compact 确保如果 array 要求array2 中不存在的键,并在 O(n) 时间内完成。

关于ruby - 将 Ruby 元组数组转换为给定键数组的散列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10942981/

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