向用户询问信息,而不必再问

我想要求用户输入,但我只想做一次(可能保存程序中的信息),意思是这样的:

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 

您需要将用户名存储在本地文件系统上的文件中。 Ruby提供了许多方法来实现这一点,我们将在这个答案中探讨一个:YAML文件。

YAML文件是一种结构化存储文件,可以存储各种不同的数据,是存储配置数据的好地方。 事实上,YAML配置文件是现有最大的Ruby项目的关键部分。 YAML为您提供了一个良好的起点,可以支持未来的配置需求,超出当前的配置需求,这是规划function开发的好方法。

那么它是怎样工作的? 让我们使用YAML配置来查看您的需求:

 require 'yaml' config_filename = "config.yml" config = {} name = nil if file_exists(config_filename) begin config = YAML.load_file(config_filename) name = config["name"] rescue ArgumentError => e puts "Unable to parse the YAML config file." puts "Would you like to proceed?" proceed = gets.chomp # Allow the user to type things like "N", "n", "No", "nay", "nyet", etc to abort if proceed.length > 0 && proceed[0].upcase == "N" abort "User chose not to proceed. Aborting!" end end end if name.nil? || (name.strip.length == 0) print "Enter your name (you will only need to do this once): " name = gets.chomp # Store the name in the config (in memory) config["name"] = name # Convert config hash to a YAML config string yaml_string = config.to_yaml # Save the YAML config string to the config file File.open(config_filename, "w") do |out| YAML.dump(config, out) end end 

这段代码不是向您展示满足您需求的最低要求,而是包含一些error handling和一些简单的安全检查配置文件。 它可能足够强大,您可以立即使用。

第一位只需要YAML标准库。 这使YAMLfunction在您的程序中起作用。 如果您有一个加载器文件或其他类似的常用机制,只需将require 'yaml'放在那里。

之后,我们初始化一些在此过程中使用的变量。 您应该注意config_filename中没有路径信息,因此它将从当前目录中读取。 您可能希望将配置文件存储在公共位置,例如~/.my-program-name/config.ymlC:\Documents and Settings\MyUserName\Application Data\MyProgramName\ 。 这可以很容易地完成,并且有很多可以提供帮助,例如在Windows中放置用户配置文件的 位置和linux / unix中的ini / config文件的位置 。

接下来,我们检查文件是否确实存在,如果是,我们尝试从中读取YAML内容。 YAML.load_file()方法处理所有繁重的工作,因此您只需要询问为您感兴趣的密钥返回的配置哈希,在本例中为"name"键。

如果在读取YAML文件时发生错误,则表明该文件可能已损坏,因此我们尝试处理该文件。 YAML文件易于手动编辑,但是当您这样做时,您也可以轻松引入错误,这将导致加载YAML文件失败。 这里的error handling代码将允许用户中止程序并返回修复YAML文件,这样它就不会被简单地覆盖。

在那之后,我们试着看看我们是否从YAML配置中获得了有效的名称,如果没有,我们继续从用户接受它。 一旦他们输入了名称,我们将其添加到配置哈希,将哈希转换为YAML格式的字符串,然后将该字符串写入配置文件。

这就是全部。 几乎任何可以存储在Ruby哈希中的东西,都可以存储在YAML文件中。 这是存储配置信息的强大function,如果您以后需要添加更多配置选项,您就拥有了一个多function容器,您可以将其用于此目的。

如果您想进一步阅读YAML,可以在这里找到一些好的信息:

  • 机器人Ruby教程中的YAML没有心脏
  • 在Juixe Techknow上使用Ruby YAML进行干扰
  • YAML挣扎于Ruby

虽然其中一些文章有点陈旧,但它们仍然非常相关,并且会为您提供进一步阅读的起点。 请享用!

如果您需要多次在运行脚本的用户之间保留名称,则需要使用某种数据存储。 尽管我讨厌平面文件,如果你要存储的只是用户的名字,我认为这是一个有效的选项。

 if File.exist?('username.txt') name = File.open( 'username.txt', 'r' ) do |file| name = file.gets end else print "Enter your name (you will only need to do this once): " name = gets.chomp File.open( 'username.txt', 'w' ) do |file| file.puts name end end str = "Hello there #{name}"