繁体   English   中英

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

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

我在我的yaml文件中有一个哈希映射,如下所示。 我如何在简单的ruby脚本中迭代它? 我希望在迭代期间将键存储在我的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

我从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

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

根据你的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' }
  ]}

然后迭代你可以采取以下方法:

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