2015-11-05 46 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"}