简体   繁体   中英

Convert YAML into an array of hashes

So I have this permissionrank.yaml file:

player:
  id: 1
  label: Player
  badge: NIL

bronze helper:
  id: 2
  label: Bronze Helper
  badge: STF_HELP_BRZ

silver helper:
  id: 3
  label: Silver Helper
  badge: STF_HELP_SLV

Is there any way to load this into an array of hashes so it would fit the same format of Rails' seeds.rb file? It should output:

[
  {id: 1, label: "Player",                badge: "NIL"        },
  {id: 2, label: "Bronze Helper",         badge: "STF_HLP_BRZ"},
  {id: 3, label: "Silver Helper",         badge: "STF_HLP_SLV"},
]

That's the format Rails' seeds file asks for.

In your example, it loads from YAML like:

{"player"=>{"id"=>1, "label"=>"Player", "badge"=>"NIL"},
 "bronze helper"=>{"id"=>2, "label"=>"Bronze Helper", "badge"=>"STF_HELP_BRZ"},
 "silver helper"=>{"id"=>3, "label"=>"Silver Helper", "badge"=>"STF_HELP_SLV"}}

So all you really seem to need to get rid of is the hash keys. If you only want to keep the values of a hash, you can use the Hash#values method to get (almost) the array you want:

pp YAML.load_file("permissionrank.yml").values

[{"id"=>1, "label"=>"Player", "badge"=>"NIL"},
 {"id"=>2, "label"=>"Bronze Helper", "badge"=>"STF_HELP_BRZ"},
 {"id"=>3, "label"=>"Silver Helper", "badge"=>"STF_HELP_SLV"}]

The only remaining difference with your example is then that the keys inside those hashes are strings, not symbols. This probably doesn't matter, since Rails is generally really relaxed about that, but just for the sake of example, let's convert those as well. For this you can use the Hash#symbolize_keys method from ActiveSupport.

pp YAML.load_file("permissionrank.yml").values.map(&:symbolize_keys)

[{id: 1, label: "Player", badge: "NIL"},
 {id: 2, label: "Bronze Helper", badge: "STF_HELP_BRZ"},
 {id: 3, label: "Silver Helper", badge: "STF_HELP_SLV"}]

Below will give you an array of hashes:

-
  :id: 1
  :label: Player
  :badge: NIL
-
  :id: 2
  :label: Bronze Helper
  :badge: STF_HELP_BRZ
-
  :id: 3
  :label: Silver Helper
  :badge: STF_HELP_SLV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM