简体   繁体   English

将数组写入文件ruby

[英]Write array to file ruby

I have array of brands. 我有很多品牌。

And I have this code: 我有这段代码:

brands.each_with_index do |brand, index|
  File.open('brands.txt', 'w') { |file| file.print  "#{brand.name} - #{brand.url}" }
end

So I want to write all brands into file but as a result I get only last brand, something like this: 所以我想将所有品牌都写入文件中,但是结果是我只得到了最后一个品牌,如下所示:

Biomill - htttp://site.com/brand/biomill/dogs/ Biomill-htttp://site.com/brand/biomill/dogs/

It seems like my file is being rewritten in the loop. 似乎我的文件正在循环中被重写。 What do I do? 我该怎么办?

You almost had it! 你差点就吃了!

File.open('brands.txt', 'w') do |file| 
  brands.each_with_index do |brand, index|
    file.print "#{brand.name} - #{brand.url}" 
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM