将数组元素转换为哈希

时间:2018-12-02 21:33:06

标签: ruby hash

我有一个包含以下元素的数组:

results = ["test=complete", "test2=passed", "test3=failed", "test4=successful"]

我想使用以下键和值将此数组转换为哈希:

results_hash = {"test": "complete", "test2": "passed", "test3": "failed", "test4": "successful"}

我该怎么做?不确定是否最好使用set,hash等。

3 个答案:

答案 0 :(得分:6)

在Ruby 2.6中:

results.to_h{|s| s.split("=").then{|k, v| [k.to_sym, v]}}
# => {:test=>"complete", :test2=>"passed", :test3=>"failed", :test4=>"successful"}

答案 1 :(得分:4)

results = ["test=complete", "test2=passed", "test3=failed", "test4=successful"]
results_hash = results.map{|str| str.split("=") }.to_h
# => {"test"=>"complete", "test2"=>"passed", "test3"=>"failed", "test4"=>"successful"}

编辑:作为@sawa注释,键应为符号。这是一种方法:

results.map{|str| a,b = str.split("="); [a.to_sym, b] }.to_h

答案 2 :(得分:0)

这是我的解决方案:

array = ['test=passed', 'test=failed']

num_of_elements = array.length 



x = array[0].split("")

y = array[1].split("")

array = x + y

x.delete_if {|x| x.match('=')}
y.delete_if {|x| x.match('=')}

test_arr = x[0..3].join()
fail = x[4..9].join()

test_arr_2 = y[0..3].join()

fail_2 = y[4..9].join()

results = {}

results.compare_by_identity

results["#{test_arr}"] = fail
results["#{test_arr_2}"] = fail_2


puts results