2015-11-05 44 views
1
散列

我有一个数组,看起来像下面的一些数据集:转换键值对数组在红宝石

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

另外,我需要将其转换为一个哈希值,如下:

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

我必须做一些错误的,因为我越来越怪异的映射与我.shift.split导致{ “名称= ABC”=> “ID = 123”}。谢谢。

回答

4

所有需要做的是在阵列的每个部分分成一个键和值(产生两个元素数组的数组),然后结果传递给手持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

你能做到这样(用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 S IN所述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"} 
+1

这是最好的答案。 – Charles

0
array.each_with_object({}) { |s,h| h.update([s.split(/\s*=\s*/)].to_h) } 
    #=> {"Name"=>"abc", "Id"=>"123", "Interest"=>"Rock Climbing"} 

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

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"} 

等。

0

试试这个

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

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