在练习19中的学习Ruby Hard The Way> 一书中,它说应该采用所提供的功能:
def cheese_and_crackers(cheese_count, boxes_of_crackers)
puts "You have #{cheese_count} cheeses!"
puts "You have #{boxes_of_crackers} boxes of crackers!"
puts "Man that's enough for a party!"
puts "Get a blanket.\n"
end
并探索不同的方法。我试着探索函数的参数并用它写一个文本:
file = ARGV.first
puts "Let's make a test?"
puts "Does the output file exist? #{File.exist?(arquivo)} "
puts "Ready, hit RETURN to continue, CTRL-C to abort."
$stdin.gets
def success(price, recipe)
puts """Text goes on like this:
In order to become a coder, You must dedicate yourself.\n
For that, you must pay a price, such as #{price}\n
Becoming a coder also requires #{recipe}\n"""
end
puts "What is the price to pay in order to become a coder?"
price = $stdin.gets
puts "What are the fundamental components in order to become a coder?"
recipe = $stdin.gets
coder = success(price, recipe)
motivational = File.open(file, 'w')
motivational.write(coder)
puts "Read this every day."
但我似乎无法让它将函数写入新的test.txt
文件中。 test.txt
文件为空。
答案 0 :(得分:4)
调用puts
时,您正在写入stdout,但返回值将为空。
改变这个:
def success(price, recipe)
return """Text goes on like this:
In order to become a coder, You must dedicate yourself.\n
For that, you must pay a price, such as #{price}\n
Becoming a coder also requires #{recipe}\n"""
end
然后:
motivational.close()
编辑:这是一个扩展的解释:当调用puts
时,你只是将字符串写入stdout,这是程序的默认输出。方法(函数)可以具有返回值。对于success
方法,您需要返回字符串,以便将其写入文件中。如果您拨打puts
而不是return
,success
方法将不会返回任何值,因此请将文件留空。
对于close()
调用,建议在脚本结束前关闭文件流。
请查看这些参考资料以获取更多信息: