Doublespeed
Doublespeed

Reputation: 1173

How to iterate through a yaml hash structure in ruby?

I have a hash mapping in my yaml file as below. How Can I iterate through it in simple ruby script? I would like to store the key in a variable and value in another variable in my ruby program during the iteration.

source_and_target_cols_map:
 -
    com_id: community_id
    report_dt: note_date
    sitesection: site_section
    visitor_cnt: visitors
    visit_cnt: visits
    view_cnt: views
    new_visitor_cnt: new_visitors

the way i am getting the data from the yaml file is below:

#!/usr/bin/env ruby

require 'yaml'

    config_options = YAML.load_file(file_name)
    @source_and_target_cols_map = config_options['source_and_target_cols_map']
puts @source_and_target_cols_map

Upvotes: 9

Views: 20765

Answers (2)

Doydle
Doydle

Reputation: 921

The YAML.load_file method should return a ruby hash, so you can iterate over it in the same way you would normally, using the each method:

require 'yaml'

config_options = YAML.load_file(file_name)
config_options.each do |key, value|
    # do whatever you want with key and value here
end

Upvotes: 7

Arup Rakshit
Arup Rakshit

Reputation: 118261

As per your yaml file it you should get the below Hash from the line config_options = YAML.load_file(file_name)

config_options = { 'source_and_target_cols_map' =>
 [  { 'com_id' => 'community_id',
    'report_dt' => 'note_date',
    'sitesection' => 'site_section',
    'visitor_cnt' => 'visitors',
    'visit_cnt' => 'visits',
    'view_cnt' => 'views',
    'new_visitor_cnt' => 'new_visitors' }
  ]}

Then to iterate through you can take the below approach:

config_options['source_and_target_cols_map'][0].each {|k,v| key = k,value = v}

Upvotes: 1

Related Questions