将每个数组元素添加到 ruby​​ 文件的行中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18900474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 06:10:57  来源:igfitidea点击:

Add each array element to the lines of a file in ruby

rubyarraysfilelineoutput

提问by edc505

If I have an array of strings e.g.

如果我有一个字符串数组,例如

a = ['a', 'b', 'c', 'd']

and I want to output the elements, to a file (e.g. .txt) one per line. So far I have:

我想将元素输出到一个文件(例如 .txt)中,每行一个。到目前为止,我有:

File.new("test.txt", "w+")
File.open("test.txt", "w+") do |i|
    i.write(a)
end

This gives me the array on one line of the test.txt file. How can I iterate over the array, adding each value to a new line of the file?

这给了我 test.txt 文件一行上的数组。如何遍历数组,将每个值添加到文件的新行?

回答by Stefan

Either use Array#eachto iterate over your array and call IO#putsto write each element to the file (putsadds a record separator, typically a newline character):

要么用于Array#each遍历数组并调用IO#puts将每个元素写入文件(puts添加记录分隔符,通常是换行符):

File.open("test.txt", "w+") do |f|
  a.each { |element| f.puts(element) }
end

Or pass the whole array to puts:

或者将整个数组传递给puts

File.open("test.txt", "w+") do |f|
  f.puts(a)
end

From the documentation:

从文档:

If called with an array argument, writes each element on a new line.

如果使用数组参数调用,则在新行上写入每个元素。

回答by Josip ?urakovi?

There is a quite simpler solution :

有一个非常简单的解决方案:

IO.write("file_name.txt", your_array.join("\n"))

回答by tigeravatar

As an alternate, you could simply join the array with "\n" so that each element is on a new line, like this:

作为替代方案,您可以简单地使用 "\n" 加入数组,以便每个元素都在一个新行上,如下所示:

a = %w(a b c d)

File.open('test.txt', 'w') {|f| f.write a.join("\n")}

If you don't want to override the values already in the text file so that you're simply adding new information to the bottom, you can do this:

如果您不想覆盖文本文件中已有的值,而只是在底部添加新信息,则可以执行以下操作:

a = %w(a b c d)

File.open('test.txt', 'a') {|f| f << "\n#{a.join("\n")}"}

回答by falsetru

Use Array#eachto iterate each element. When writing to the file, make sure you append newline(\n), or you will get a file with abcdas content:

使用Array#each迭代每个元素。写入文件时,请确保附加换行符( \n),否则您将得到一个abcd内容如下的文件:

a = ['a', 'b', 'c', 'd']
File.open('test.txt', 'w') do |f|
  a.each do |ch|
    f.write("#{ch}\n")
  end
end

回答by andriy

Another simple solution:

另一个简单的解决方案:

directory = "#{Rails.root}/public/your_directory" #create your_directory before
file_name = "your_file.txt"
path = File.join(directory, file_name)
File.open(path, "wb") { |f| f.write(your_array.join("\n")) }