Ruby on rails 将数组写入文件ruby
我有很多品牌 我有这个密码:Ruby on rails 将数组写入文件ruby,ruby-on-rails,ruby,Ruby On Rails,Ruby,我有很多品牌 我有这个密码: brands.each_with_index do |brand, index| File.open('brands.txt', 'w') { |file| file.print "#{brand.name} - #{brand.url}" } end 因此,我想将所有品牌写入文件,但结果我只得到最后一个品牌,如下所示: 生物制药htttp://site.com/brand/biomill/dogs/ 我的文件好像在循环中被重写。 我该怎么办?你差一点就拿到
brands.each_with_index do |brand, index|
File.open('brands.txt', 'w') { |file| file.print "#{brand.name} - #{brand.url}" }
end
因此,我想将所有品牌写入文件,但结果我只得到最后一个品牌,如下所示:
生物制药htttp://site.com/brand/biomill/dogs/
我的文件好像在循环中被重写。
我该怎么办?你差一点就拿到了
File.open('brands.txt', 'w') do |file|
brands.each_with_index do |brand, index|
file.print "#{brand.name} - #{brand.url}"
end
end
你差点就成功了
File.open('brands.txt', 'w') do |file|
brands.each_with_index do |brand, index|
file.print "#{brand.name} - #{brand.url}"
end
end
当然,您的文件在每个循环中都会被重写。您的代码完全按照您编写它的目的进行操作。当然,您的文件在每个循环中都会被重写。你的代码正在做你写它要做的事情。我在2分钟前发现了这个,但是谢谢!我可以在10分钟内接受答案。我在2分钟前发现了这个问题,但谢谢!我可以在10分钟内接受答复。