【问题标题】:Ruby loop question and dumping results into YAML fileRuby 循环问题并将结果转储到 YAML 文件中
【发布时间】:2011-05-17 13:37:36
【问题描述】:

我正在编写一个 Ruby 脚本,它将一个键值对转储到一个 yaml 文件中。但由于某种原因,我的循环只抓取了循环中的最后一个实例。应该有多个键值对。

代码:

# Model for languages Table
class Language < ActiveRecord::Base
end

# Model for elements Table
class Element < ActiveRecord::Base
  has_many :element_translations
end

# Model for element_translations Table
class ElementTranslation < ActiveRecord::Base
  belongs_to :element
end

# Find ALL languages
lang = Language.all
# Get all elements
elements = Element.where("human_readable IS NOT NULL")
info = ''

elements.each do |el|
  lang.each do |l|
    et = el.element_translations.where("language_id = ?", l.id)
    et.each do |tran|
      info = {
        el.human_readable.to_s => tran.content.to_s
      }
    end
    File.open(l.code.to_s + ".yml", "w", :encoding => "UTF-8") do |f|
      YAML.dump(info, f)
    end
  end
end

有什么想法吗?

【问题讨论】:

    标签: ruby yaml


    【解决方案1】:

    当你这样做时:

    info = {
      el.human_readable.to_s => tran.content.to_s
    }
    

    你的意思是:

    info << {
      el.human_readable.to_s => tran.content.to_s
    }
    

    否则你每次都只是重新分配info

    如果您要这样做,请将 info 设为数组:info = [] 而不是 info = ''

    【讨论】:

    • 谢谢你!这就像一个魅力!不过我有一个新问题。我的数据库中有 UTF-8 字符,但是当我将数据转储到我的 YAML 文件时,我得到? UTF-8 字符应该在哪里......对此有什么想法吗?
    • @dennis - 可能值得在单独的问题中提问。
    • 我实际上能够找出我的问题...这是我的最新问题...由于某种原因,每次循环发生时,数组都没有被重置。所以转储到每个 YAML 文件中的值不仅是新的数组值,而且是以前的值......
    【解决方案2】:

    在这个循环中

    et.each do |tran|
      info = {
        el.human_readable.to_s => tran.content.to_s
      }
    end
    

    您使用具有不同值的一个键 el.human_readable.to_s 重复创建新哈希。但是,即使您将其重做为

    info = {}
    et.each do |tran|
      info[el.human_readable.to_s] = tran.content.to_s
    end
    

    您不会得到超过 1 个结果,因为键不会改变 - 您只会重复地为其分配不同的值。你到底想甩掉什么?可能你想要一个数组,而不是键值映射?

    info_array = []
    et.each do |tran|
      info_array << tran.content.to_s
    end
    info = { el.human_readable.to_s => info_array }
    

    【讨论】:

      猜你喜欢
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 2020-08-05
      相关资源
      最近更新 更多