9

以下のように、yaml ファイルにハッシュ マッピングがあります。簡単なルビースクリプトでそれを繰り返すにはどうすればよいですか? 反復中に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
4

2 に答える 2

7

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-07-16T13:38:19.717 に答える
1

ファイルに従って、行からyaml以下を取得する必要がありますHashconfig_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' }
  ]}

次に、反復するには、以下のアプローチを取ることができます。

config_options['source_and_target_cols_map'][0].each {|k,v| key = k,value = v}
于 2013-07-16T13:32:23.220 に答える