Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into hashes

Tags:

arrays

ruby

hash

I have an array of values. For example:

arr = [
           "1", "customer_one", "down",
           "2", "up",
           "3", "down",
           "4", "customer_two", "up",
           "5", "for_vpn", "down"
         ]

These values describe ports info of router. I want to get array of hashes something like this:

[
  {: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"}
]

Please note that between arr[3] and arr[4], arr[5] and arr[6] there is no element that has description value but the result hash must contain key description equals to empty string :description=>""

like image 277
Victor Borshchov Avatar asked Apr 07 '26 12:04

Victor Borshchov


1 Answers

arr
.slice_before{|e| e !~ /\D/}
.map do
  |name, description = "", state|
  {name: name, description: description, state: state}
end
like image 156
sawa Avatar answered Apr 09 '26 01:04

sawa