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中将每个数组元素添加到文件的行中_Ruby_Arrays_File_Line_Output - Fatal编程技术网

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

在ruby中将每个数组元素添加到文件的行中,ruby,arrays,file,line,output,Ruby,Arrays,File,Line,Output,如果我有一个字符串数组,例如 a = ['a', 'b', 'c', 'd'] 我想将元素输出到一个文件(例如,txt),每行一个。到目前为止,我已经: File.new("test.txt", "w+") File.open("test.txt", "w+") do |i| i.write(a) end 这在test.txt文件的一行中给出了数组。 如何迭代数组,将每个值添加到文件的新行?用于迭代每个元素。写入文件时,请确保追加换行符(\n),否则将得到一个包含abcd内容的文件:

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

a = ['a', 'b', 'c', 'd']
我想将元素输出到一个文件(例如,txt),每行一个。到目前为止,我已经:

File.new("test.txt", "w+")
File.open("test.txt", "w+") do |i|
    i.write(a)
end
这在test.txt文件的一行中给出了数组。 如何迭代数组,将每个值添加到文件的新行?

用于迭代每个元素。写入文件时,请确保追加换行符(
\n
),否则将得到一个包含
abcd
内容的文件:

a = ['a', 'b', 'c', 'd']
File.open('test.txt', 'w') do |f|
  a.each do |ch|
    f.write("#{ch}\n")
  end
end
使用迭代数组并调用将每个元素写入文件(
put
添加记录分隔符,通常是换行符):

或者将整个数组传递给
puts

File.open("test.txt", "w+") do |f|
  f.puts(a)
end
从文件中:

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


作为替代方案,您可以简单地用“\n”连接数组,使每个元素位于新行上,如下所示:

a = %w(a b c d)

File.open('test.txt', 'w') {|f| f.write a.join("\n")}
如果不想覆盖文本文件中已有的值,以便只需在底部添加新信息,可以执行以下操作:

a = %w(a b c d)

File.open('test.txt', 'a') {|f| f << "\n#{a.join("\n")}"}
a=%w(a b c d)

File.open('test.txt','a'){| f | f有一个非常简单的解决方案:

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

另一个简单的解决方案:

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")) }

@SergioTulentsev,看。没有
每一个
。什么?这些年来我一直认为每一个都属于可枚举的。@SergioTulentsev,
可枚举的
只是一个混搭。它没有定义
每一个
本身。对,这取决于
每一个
。你的第一个建议就是我想要的。谢谢。只是提醒一下使用内置程序的人数组的替代:只有第一个版本有效。@danielf。这是正确的,正如文档中提到的,您必须使用数组参数调用
puts
,才能获得该行为。@Dika Suparlan,欢迎这样做。一点解释也很有帮助。它不仅验证了您的答案,而且还为OP提供了他们需要的指示既要处理当前问题,也要处理未来可能出现的问题。我确信我不是唯一一个想向SO社区学习而不是仅仅得到解决方案的人。最大的成功感在于克服一个好的挑战。;-)这应该是首选答案。从文档--IO.write(name,string[,offset][,opt])→ 整数---打开文件,可选地查找给定的偏移量,写入字符串,然后返回写入的长度。写入确保文件在返回之前关闭。如果未给定偏移量,则文件被截断。否则,不会截断。
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")) }