我承认我还是Ruby的新手,所以我还不熟悉这些问题而且还在学习。
我已多次搜索该问题,但未能找到确切的答案。大多数结果都讨论了“嵌套”if / else语句。这不是我正在尝试的。我找到了SO的另一个答案,谈到了根据条件映射数组,但感觉这会让我回到我已经拥有的相同问题。
如果有兴趣的话,链接到关于合并嵌套数组的SO文章:Ruby: Merging nested array between each other depending on a condition
我的问题:
在ruby中使用optparse设计一个简单的CLI脚本来控制基于条件的输出。我遇到了一个问题,我无法执行多个顺序if语句,并将多个数组连接/合并为一个传递给另一个函数。
出于某种原因,只有最后一个if块被尊重。在最后一个之前的所有if块返回nil。
任何人都可以告诉我我做错了什么,并提供有关我的问题的一些相关文件。比如为什么会出现这样的问题?
我们喜欢一个可以学习的工作解决方案,但是参考材料也会起作用,因为我的目标是从这个问题中学习。
我的测试结果:
$ ruby servers.rb
#=> ["server1", "server2", "server3"]
$ ruby servers.rb -m
#=> nil
$ ruby servers.rb -h
#=> nil
$ ruby servers.rb -s server6
#=> ["server6"]
$ ruby servers.rb -m -h
#=> nil
以下是我的脚本:
#!/usr/bin/env ruby
require 'optparse'
@servers = {
'primary' => %w[server1 server2 server3],
'inhouse' => %w[server4 server5],
'mlm' => %w[server6]
}
@options = {
inhouse: false,
server: [],
mlm: false
}
# Parse options passed to medusabackup.rb
optparse = OptionParser.new do |opts|
opts.on('-h', '--inhouse', 'Limit results to inhouse results') do
@options[:inhouse] = true
end
opts.on('-m', '--mlm', 'Include mlm results') do
@options[:mlm] = true
end
opts.on('-s', '--server=SERVER', 'Limit results to SERVER') do |f|
@options[:server] << f
end
opts.on_tail('--help', 'Display this screen') { puts opts, exit }
end
begin
optparse.parse!
rescue OptionParser::InvalidOption, OptionParser::MissingArgument
puts $ERROR_INFO.to_s
puts optparse
exit
end
def selected_servers
# Setup Selected variable as an array
selected = []
# If @options[:server] array is not empty and @options[:server]
# add @options[:server] servers to [selected] array
if @options[:server].empty?
# If @options[:mlm] is true add @server['mlm'] servers to [selected] array
selected.concat @servers['mlm'] if @options[:mlm]
# If @options[:inhouse] is true add @server['inhouse'] servers to [selected] array
selected.concat @servers['inhouse'] if @options[:inhouse]
# If @options[:mlm], @options[:inhouse] is true add @server['mlm'] servers to [selected] array
selected.concat @servers['primary'] unless @options[:mlm] || @options[:inhouse]
else
selected.concat @options[:server]
end
end
puts selected_servers.inspect
感谢Max和所有人向我展示我的错误。忘记在函数底部选择返回。
在selected_servers
中没有明确的返回,所以它返回它运行的最后一个表达式的值,这通常是一个失败的unless
。如果/除非失败,则返回nil
。