我在数组中有一些类似于以下内容的数据集:
array = [ "Name = abc", "Id = 123", "Interest = Rock Climbing" ]
我需要将其转换为哈希,如下所示:
hash = { "Name" => "abc", "Id" => "123", "Interest" => "Rock Climbing" }
我必须做错事,因为我与.shift.split进行了奇怪的映射,导致{“Name = abc”=>“Id = 123”}。感谢。
答案 0 :(得分:6)
您需要做的就是将数组的每个部分拆分为一个键和值(产生一个双元素数组的数组),然后将结果传递给方便的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" }
答案 1 :(得分:2)
你可以这样做(使用Enumerable#each_with_object):
array.each_with_object({}) do |a, hash|
key,value = a.split(/\s*=\s*/) # splitting the array items into key and value
hash[key] = value # storing key => value pairs in the hash
end
# => {"Name"=>"abc", "Id"=>"123", "Interest"=>"Rock Climbing"}
如果您发现each_with_object
有点难以理解,可以采用天真的方式(仅在key
累积value
和result_hash
) :
result_hash = {}
array.each do |a|
key,value = a.split(/\s*=\s*/) # splitting the array items into key and value
result_hash[key] = value # storing key => value pairs in the result_hash
end
result_hash
# => {"Name"=>"abc", "Id"=>"123", "Interest"=>"Rock Climbing"}
答案 2 :(得分:0)
试试这个
array.map {|s| s.split('=')}.to_h
=> {"Name "=>" abc", "Id "=>" 123", "Interest "=>" Rock Climbing"}