1

我是ruby新手,犯了很多错误,所以希望对ruby有经验的人可以分享一点知识。我不知道如何让 ruby​​ 将文本保存到方法all写入的 txt 文件中。

class generator
  def all
    puts "i want to save this text into a txt file"
  end
end
new_gen = generator.new
new_gen.all

my_file = File.new("Story.txt", "a+")
my_file.puts("all")
my_file.puts("\n")
my_file.close

我尝试了所有方法,但 txt 文件要么包含“全部”,要么完全空白。有任何想法吗?我也试过my_file.puts(all)my_file.puts(new_gen.all)

4

3 回答 3

1

您的方法应该只返回一个字符串。Puts 显示字符串,不返回它。因此,将类更改为:

class generator
  def all
    "i want to save this text into a txt file" # optionally add a return
  end
end
new_gen = generator.new
new_gen.all

然后使用您尝试过的最后一个版本:my_file.puts(new_gen.all)

于 2013-03-22T16:19:31.960 回答
1

试试这个:

class Generator
  def all
    "i want to save this text into a txt file"
  end
end

gen = Generator.new

f = File.new("Story.txt", "a+")
f.puts gen.all
f.close
于 2013-03-22T16:21:51.797 回答
1

如果你想做Generator写作,你可以把它传递给一个IO对象。

class Generator
  def initialize(io)
    @io = io
  end

  def all
    @io.puts "i want to save this text into a txt file"
  end
end

# write to STDOUT
gen = Generator.new(STDOUT)
gen.all

# write to file
File.open("Story.txt", "a+") do |file|
  gen = Generator.new(file)
  gen.all
end
于 2013-03-22T16:54:01.510 回答