Ruby将数组转换为哈希

时间:2014-06-25 20:22:16

标签: ruby arrays string

我有以下字符串,我想将其转换为哈希打印以下结果

string = "Cow, Bill, Phone, Flour"

hash = string.split(",")

>> {:animal => "Cow", :person: "Bill", :gadget => "Phone", 
    :grocery => "Flour"}

2 个答案:

答案 0 :(得分:1)

hash = Hash[[:animal, :person, :gadget, :grocery].zip(string.split(/,\s*/))]

答案 1 :(得分:0)

@Max的答案非常好。你可能会更好地理解它:

def string_to_hash(str)
  values = str.split(/,\s*/)
  names = [:animal, :person, :gadget, :grocery]
  Hash[names.zip(values)]
end

这是一种不太复杂的方法:

def string_to_hash(str)
  parts = str.split(/,\s*/)
  Hash[
    :animal  => parts[0],
    :person  => parts[1],
    :gadget  => parts[2],
    :grocery => parts[3],
  ]
end