【问题标题】:Ruby conditional statementRuby 条件语句
【发布时间】:2012-02-01 07:01:51
【问题描述】:

我有这样的情况:

if connection
  if "name" == connection.name
    ...
  end
end

connection 最初可能有nil 值,所以我无法检查if connection && "name" == connection.name

如何有效地简化条件?

【问题讨论】:

    标签: ruby-on-rails ruby string oop conditional-statements


    【解决方案1】:
    unless connection.nil? || connection.name != "name"
      #...Statements
    end
    

    【讨论】:

      【解决方案2】:
      if connection and connection.name == "name"
         ...
      end
      

      【讨论】:

      • 比上面的否定版本更容易阅读和理解。
      猜你喜欢
      • 1970-01-01
      • 2015-11-26
      • 2014-07-27
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      • 1970-01-01
      • 2019-05-22
      相关资源
      最近更新 更多