简体   繁体   English

如何遍历ruby中的yaml哈希结构?

[英]How to iterate through a yaml hash structure in ruby?

I have a hash mapping in my yaml file as below. 我在我的yaml文件中有一个哈希映射,如下所示。 How Can I iterate through it in simple ruby script? 我如何在简单的ruby脚本中迭代它? I would like to store the key in a variable and value in another variable in my ruby program during the iteration. 我希望在迭代期间将键存储在我的ruby程序中的另一个变量中的变量和值中。

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: 我从yaml文件获取数据的方式如下:

#!/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: YAML.load_file方法应返回一个ruby哈希,因此您可以使用每种方法以与通常相同的方式迭代它:

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) 根据你的yaml文件,你应该从行config_options = YAML.load_file(file_name)获得以下Hash

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}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM