【发布时间】:2016-09-02 00:01:24
【问题描述】:
我想询问用户输入,但我只想做一次(可能将信息保存在程序中),意思是这样的:
print "Enter your name (you will only need to do this once): "
name = gets.chomp
str = "Hello there #{name}" #<= As long as the user has put their name in the very first
# time the program was run, I want them to never have to put thier name in again
我怎样才能在 Ruby 程序中做到这一点?
该程序将由多个用户全天在多个系统上运行。我试图将它存储到内存中,但显然失败了,因为据我了解,每次 Ruby 程序停止执行时都会擦除内存。
我的尝试:
def capture_user
print 'Enter your name: '
name = gets.chomp
end
#<= works but user has to put in name multiple times
def capture_name
if File.read('name.txt') == ''
print "\e[36mEnter name to appear on email (you will only have to do this once):\e[0m "
@esd_user = gets.chomp
File.open('name.txt', 'w') { |s| s.puts(@esd_user) }
else
@esd_user = File.read('name.txt')
end
end
#<= works but there has to be a better way to do this?
require 'tempfile'
def capture_name
file = Tempfile.new('user')
if File.read(file) == ''
print "\e[36mEnter name to appear on email (you will only have to do this once):\e[0m "
@esd_user = gets.chomp
File.open(file, 'w') { |s| s.puts(@esd_user) }
else
@esd_user = File.read(file)
end
end
#<= Also used a tempfile, this is a little bit over kill I think,
# and doesn't really help because the users can't access their Appdata
【问题讨论】:
-
你的问题为时过早。你试过什么?为什么它不起作用?如果你还没有尝试过,为什么不呢?您的示例没有显示任何尝试,这就是我们需要看到的。请阅读“How to Ask”(包括该页面中的链接)和“minimal reproducible example”。照原样,您要求提供教程,但我们不知道您的专业知识是什么,因此我们必须从最底层开始工作,这是题外话。多个用户/时间?来自不同的系统?从一个系统?使用浏览器?从命令行?有很多缺失的信息。
-
@theTinMan 怎么样?
-
这是一个改进。保存的信息是只对那台机器上的个人有用,还是对所有机器上的每个人都有用?原因是,保存文件只对特定机器上的个人有用。如果您需要共享您需要使用共享数据存储库(通常是数据库)的信息。
-
您不能将 Tempfile 用于您的目的。它旨在创建一个仅在脚本执行期间存在的临时文件。一旦脚本退出,文件就会被删除。所以不是问这个的地方。您需要阅读一些文件教程,了解保存数据的各种方法(平面文本文件,与本地简单数据库,与使用 YAML 或 JSON 的序列化结构),尝试一下,然后当您有代码有问题问一个问题。
标签: ruby user-input