Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 将数组写入文件ruby_Ruby On Rails_Ruby - Fatal编程技术网

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分钟内接受答复。