简体   繁体   中英

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

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

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}

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