【问题标题】:How to iterate through a yaml hash structure in ruby?如何遍历 ruby​​ 中的 yaml 哈希结构?
【发布时间】:2013-07-14 16:40:25
【问题描述】:

我的 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中没有那个键'source_table'
  • 是的,我知道。它只是一个例子。如何让它呈现出来,以便我可以遍历键值对的值?

标签: ruby-on-rails ruby yaml


【解决方案1】:

根据您的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}

【讨论】:

  • 好的,yaml 不起作用。我认为我的 yaml 有问题。 couldn't parse YAML at line 8 column 1 (Psych::SyntaxError)
  • @user2081579 是的,您发布的 YAML 无效。但是你应该得到我给你的 Hash 。然后你可以使用each方法访问内部的Hash
【解决方案2】:

YAML.load_file 方法应该返回一个 ruby​​ 哈希值,因此您可以像往常一样使用 each 方法对其进行迭代:

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

【讨论】:

    猜你喜欢
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多