将键值对数组转换为 Ruby 中的散列

Converting array of key value pairs to hash in Ruby

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

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

我需要将其转换为散列:

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

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

你可以这样做(使用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有点难理解,你可以天真地理解(只是把keyvalue累加到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"}

您需要做的就是将数组的每个部分拆分为一个键和一个值(生成一个包含两个元素的数组),然后将结果传递给方便的 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" }
array.each_with_object({}) { |s,h| h.update([s.split(/\s*=\s*/)].to_h) }
  #=> {"Name"=>"abc", "Id"=>"123", "Interest"=>"Rock Climbing"} 

对于 2.0 之前的 Ruby 版本(引入 Array#to_h 时)将 [s.split(/\s*=\s*/)].h 替换为 Hash[[s.split(/\s*=\s*/)]]。 步骤:

enum = array.each_with_object({})
  #=> #<Enumerator: ["Name = abc", "Id = 123",
  #     "Interest = Rock Climbing"]:each_with_object({})>

我们可以通过将其转换为数组来查看此枚举器的元素:

enum.to_a
  #=> [["Name = abc", {}], ["Id = 123", {}], ["Interest = Rock Climbing", {}]] 

enum的第一个元素传给块,块变量赋值:

s,h = enum.next
  #=> ["Name = abc", {}] 
s #=> "Name = abc" 
h #=> {} 

并进行分块计算:

h.update([s.split(/\s*=\s*/)].to_h)
  #=> h.update([["Name", "abc"]].to_h) 
  #   {}.update({"Name"=>"abc"})
  #   {"Name"=>"abc"}

这是h的更新值。

传递给块的 enum 的下一个元素是:

s,h = enum.next
  #=> ["Id = 123", {"Name"=>"abc"}] 
s #=> "Id = 123" 
h #=> {"Name"=>"abc"} 

h.update([s.split(/\s*=\s*/)].to_h)
  #=> {"Name"=>"abc", "Id"=>"123"}

等等。

试试这个

array.map {|s| s.split('=')}.to_h

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