Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 527
Doublespeed Avatar asked Jul 16 '13 13:07

Doublespeed


2 Answers

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
like image 91
Doydle Avatar answered Oct 14 '22 18:10

Doydle


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}
like image 41
Arup Rakshit Avatar answered Oct 14 '22 16:10

Arup Rakshit