【问题标题】:in Ruby, how do I write array elements into txt file such that each element is on a separate line?在 Ruby 中,如何将数组元素写入 txt 文件,以使每个元素位于单独的行上?
【发布时间】:2019-04-15 19:03:04
【问题描述】:

我很难以每行 1 个元素的形式将数组元素写入文本文件。在这个实例中,数组是建立在句子 (.) 之上的。

请参见下面代码中的 cmets:

puts "enter paragraph:"
para = gets.chomp.to_s
my_array = []

para.split('.').each { |p| my_array << p+ '.'; print "pushed #{p}.";puts}
new_text = File.new("new_text.txt", "w+")
p my_array
my_array.each { |m| new_text.write(m)} #clearly iterating over my_array.
#.each should be writing each element on a different line, no?  Where have I gone wrong?
new_text.seek(0)

#text file is still stored in new_text variable
#the read out shows elements are not written per line
line = 1
new_text.each do |n|
    puts "line #{line}: #{n}"
    line += 1
    end

【问题讨论】:

  • 将数组arr 的每个元素(字符串)写入文件的一种方法是File.write(filename, arr.join("\n")),每个元素一行。

标签: ruby file iteration each element


【解决方案1】:

.each should be writing each element on a different line? no

不,你是否在迭代某些东西并不重要。重要的是你如何写入文件。

目前您使用的是IO#write,它没有说明添加换行符。如果您将 new_text.write 更改为 new_text.puts (IO#puts),您将在数组中的每个元素之后写一个新行。

您可以直接使用$stdout 轻松查看:

> a = %w(foo bar)
 => ["foo", "bar"] 
> a.each(&$stdout.method(:write)) # write -- no newlines
foobar => ["foo", "bar"] 
> a.each(&$stdout.method(:puts))  # puts  -- newlines
foo
bar
 => ["foo", "bar"] 

【讨论】:

  • 我的错误。我已经删除了错误的问题。
  • 另外,值得注意的是,new_text.puts(my_array) 将完全按照您的意愿行事,即使没有任何显式循环 - puts 默认情况下每行打印一个数组。
猜你喜欢
  • 1970-01-01
  • 2015-03-07
  • 2020-06-17
  • 2023-01-18
  • 1970-01-01
  • 2021-05-29
  • 1970-01-01
  • 2013-09-24
  • 1970-01-01
相关资源
最近更新 更多