[英]Ruby converting an array to a hash
我有以下字符串,我想將其轉換為打印以下結果的哈希
string = "Cow, Bill, Phone, Flour"
hash = string.split(",")
>> {:animal => "Cow", :person: "Bill", :gadget => "Phone",
:grocery => "Flour"}
hash = Hash[[:animal, :person, :gadget, :grocery].zip(string.split(/,\s*/))]
@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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.