gpt4 book ai didi

arrays - 将字符串化键值对数组转换为 Ruby 中的哈希

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

我在数组中有一些键值对字符串:

array = [ "Name = abc", "Id = 123", "Interest = Rock Climbing" ]

我需要将其转换为散列:

hash = { "Name" => "abc", "Id" => "123", "Interest" => "Rock Climbing" }

我一定是做错了什么,因为我的 .shift.split 得到了奇怪的映射,导致 {"Name=abc"=>"Id=123"}.

最佳答案

您需要做的就是将数组的每个部分拆分为键和值(产生一个双元素数组),然后将结果传递给方便的 Hash[] 方法:

arr = [ "Name = abc", "Id = 123", "Interest = Rock Climbing" ]

keys_values = arr.map {|item| item.split /\s*=\s*/ }
# => [ [ "Name", "abc" ],
# [ "Id", "123" ],
# [ "Interest", "Rock Climbing" ] ]

hsh = Hash[keys_values]
# => { "Name" => "abc",
# "Id" => "123",
# "Interest" => "Rock Climbing" }

关于arrays - 将字符串化键值对数组转换为 Ruby 中的哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536207/

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