用红宝石迭代Yaml数组 [英] Iterate a yaml array with ruby

查看:53
本文介绍了用红宝石迭代Yaml数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 YAML.load_file 应用于示例文件:

---
languages:
  - name: "English"
    iso_639: "en"
    native_name: "English"
    region:
      - ''
      - UK
      - US
  - name: "Klingon"
    iso_639: "tlh"
    native_name: "tlhIngan Hol"
    region:
      - notearth

我想遍历这些语言和区域数组。这不起作用:

I want to iterate though these languages and the region arrays. This doesn't work:

records.each do |record|
  record.region.each do |region|
    self.create!
  end
end

record.region 给了我一个地区的未知方法错误。如何遍历语言及其地区?或者,如何访问区域数组?

record.region gives me an unknown method error for region. How can I iterate though the languages and and their regions? Or, how can I access the region array?

推荐答案

您的代码中有两个错误:

There are two errors in your code:


  1. 加载YAML文件后获得的对象不是数组,而是一个哈希,例如,该文件名为 foo.yml。

YAML.load_file('foo.yml')
# => {"languages"=>[{"name"=>"English", "iso_639"=>"en", ...

因此,您必须像下面那样修改代码才能使其起作用:

Thus you have to modify your code like the following to make it work:

records['languages'].each do |record|
  # ...


  • 地区不是哈希 record 的方法,它是一个密钥,您必须使用 record ['region' ]

  • region is not a method of the hash record, it is a key, you have to access the related value using record['region'].

    您必须使用的正确代码是:

    The correct code you have to use is:

    records['languages'].each do |record|
      record['region'].each do |region|
        # My guess is you are going to use `region` inside this block
        self.create!
      end
    end
    

    这篇关于用红宝石迭代Yaml数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆