我正在编写一个与 GitHub 环境交互的脚本。对于某些用例,我需要将脚本的范围限制为用户列表,并将其存储在换行符分隔的文件中。我想将用户列表的 filename 作为参数传递给脚本,并将文件名的字符串存储在变量中,然后使用该变量稍后在脚本中按文件名打开/处理用户列表文件。
我的问题完全在于正确输入和存储文件名。假设用户列表位于名为“user-list”的文件中,其中包含以下文本:
user1
user2
user3
我想将文件名(“user-list”)存储在变量中,但我实际存储的是用户列表([“user1”,“user2”,“user3”])。
我觉得我在这里遗漏了一些非常明显的东西,但我无法在 OptionParser 文档或任何其他 Ruby 文档中找到任何相关内容。我也是一个相当新的 Ruby 用户,正在使用现有的代码库,所以如果有更好的方法来做到这一点,我还没有意识到。 这是我正在使用的代码片段:
# Initialize options OpenStruct
options = OpenStruct.new
...
# Parse arguments
option_parser = OptionParser.new do |opts|
...
opts.on("-u", "--user-file USER_FILE", String,
"Read users from a file. File should be newline separated.") do |user_file|
# FIXME: This doesn't work
# Check if the file exists
#unless File.exist?(user_file)
# puts "File not found: #{user_file}"
# exit
#end
options.user_file = user_file
# FIXME: Testing what was stored
puts options.user_file
end
...
option_parser.parse!(ARGV)
这是我传递到脚本中的内容:
./my_script -u user-file
文件“用户文件”存在,内容为:
user1
user2
user3
我试图将字符串“user-file”存储在变量
user_file
中,但我实际存储的是列表[“user1”,“user2”,“user3”]。
require 'optparse'
require 'ostruct'
options = OpenStruct.new
option_parser = OptionParser.new do |opts|
opts.on('-u', '--user-file USER_FILE', String,
'Read users from a file. File should be newline separated.') do |user_file|
options.user_file = user_file
puts options.user_file
end
end
option_parser.parse!(ARGV)