Ruby 循环问题并将结果转储到 YAML 文件中
我正在编写一个 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
有什么想法吗?
I am working on a Ruby script that will dump a key, value pair into a yaml file. But for some reason my loop is only grabbing the last instance in the loop. There should be multiple key value pairs.
Code:
# 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
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您这样做时:
您的意思是:
否则您只是每次重新分配
info
。如果您打算这样做,请将 info 设置为数组:
info = []
,而不是info = ''
。When you do:
did you mean:
Otherwise you're just re-assigning
info
each time.If you're going to do this, make info an array:
info = []
as opposed toinfo = ''
.在此循环中,
您使用具有不同值的一个键
el. human_read.to_s
重复创建新哈希。然而,即使您重做它,因为您不会得到超过 1 个结果,因为键没有改变 - 您只需重复为其分配不同的值。你到底想被甩什么?也许您想要一个数组,而不是键值映射?
In this loop
you repeatedly create new hash with one key
el.human_readable.to_s
with different values. However, even if you'll redo it asyou won't get more than 1 result, because key isn't changing - you'll just repeatedly assign it different values. What exactly do you want to get dumped? May be you'd want an array here, not key-value map?