Melvin Sowah
Melvin Sowah

Reputation: 730

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.

Upvotes: 1

Views: 3053

Answers (2)

yiwen
yiwen

Reputation: 1074

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

Upvotes: 0

Marten Veldthuis
Marten Veldthuis

Reputation: 1910

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"}]

Upvotes: 4

Related Questions