如果忽略条件,为什么最顶层?

时间:2019-03-14 20:37:31

标签: ruby conditional optparse

我承认我还是Ruby的新手,所以我还不了解陷阱,并且还在学习。

我已多次搜索该问题,但无法找到确切答案。大多数结果都谈论“嵌套” if / else语句。这不是我要尝试的。我从SO中找到了另一个答案,该答案涉及基于条件映射数组,但感觉那样会使我回到已经遇到的相同问题上。

如果有人感兴趣,请链接至SO文章,该文章涉及合并嵌套数组: Ruby: Merging nested array between each other depending on a condition

我的问题:

在使用optparse设计基于ruby的简单CLI脚本时,可根据条件控制输出。我遇到了一个问题,我无法执行多个顺序的if语句,并将多个数组concat /合并到一个数组中以传递给另一个函数。

出于某种原因,仅纪念了最后一个 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和每个人都向我展示了我的失误。忘记返回在功能底部选择的内容。

1 个答案:

答案 0 :(得分:2)

selected_servers中没有明确的返回值,因此它返回的是它运行的最后一个表达式的值,通常是失败的unless。如果失败,则返回nil