我有一个值数组。例如:
arr = [
"1", "customer_one", "down",
"2", "up",
"3", "down",
"4", "customer_two", "up",
"5", "for_vpn", "down"
]
这些值描述了路由器的端口信息。我想得到这样的哈希数组:
[
{:name=>"1", :description=>"customer_one", :state=>"down"},
{:name=>"2", :description=>"", :state=>"up"},
{:name=>"3", :description=>"", :state=>"down"},
{:name=>"4", :description=>"customer_two", :state=>"up"},
{:name=>"5", :description=>"for_vpn", :state=>"down"}
]
请注意,在
arr[3]
和 arr[4]
、 arr[5]
和 arr[6]
之间没有具有描述值的元素,但结果哈希必须包含等于空字符串 :description=>""
的键描述 最佳答案
arr
.slice_before{|e| e !~ /\D/}
.map do
|name, description = "", state|
{name: name, description: description, state: state}
end
关于arrays - 将数组拆分为散列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34692228/