Glitch_Znab
Glitch_Znab

Reputation: 586

Retrieve data from YAML and convert each value as its own array

I have this in my yml file

members: 
  - id: 1
    name: Sam
  - id: 18
    name: tom

After retrieving data from this file in a rails application I want to convert it to an array. for example

id=[1,18]
name=[sam,tom]

how can I achieve this?

Currently This is how I am retrieving the data.

yml = YAML.load_file("mem.yml")

And this is how i get my data

[{"id":1, "name":"Sam"},{"id":18, "name":"tom"}]

if I use yml["members"][1]["id"] I get the first id.

I also tried writing id and name separately like below. This does give me what I want when I use yml["id"]but I don't want to use it because of its readability. BTW my data is static.

id:
 - 1
 - 18
name:
 - Sam
 - tom

Upvotes: 0

Views: 267

Answers (1)

user11350468
user11350468

Reputation: 1407

Try the below:

yml = [{"id":1, "name":"Sam"},{"id":18, "name":"tom"}]

result = {}.tap do |result|
           yml.each do |hash|       # Iterate over array of hashes on parsed input from YAML file
             hash.each do |key, value|      # Iterate over each keys in the hash 
               result[key] ||= []           
               result[key] << value         # Append element in the array
             end
           end
         end

This will return the result as a hash:

{:id=>[1, 18], :name=>["Sam", "tom"]}

You can access the ids and names as

result[:id]   # [1, 18]
result[:name] # ["Sam", "tom"]

Upvotes: 2

Related Questions