【问题标题】:what does ? ? mean in ruby [duplicate]什么? ?红宝石的意思[重复]
【发布时间】:2015-07-14 12:26:22
【问题描述】:

下面的行检查和执行什么?

prefix = root_dir.nil? ? nil : File.join(root_dir, '/')

这是包含这行代码的块。

def some_name(root_dir = nil, environment = 'stage', branch)
        prefix = root_dir.nil? ? nil : File.join(root_dir, '/')
.
.
. 

我知道'?'在红宝石中是检查是/否履行的东西。但是我对上面代码块中的用法/语法不是很清楚。

【问题讨论】:

  • 一个问号是方法名的一部分,另一个是三元组的一部分。
  • 这里是你可以理解的格式(顺便说一下这个伪代码)。 if root_dir == nil { return nil } else { return File.join(root_dir, '/')。然后获取条件返回的内容并将其分配给变量prefix

标签: ruby-on-rails ruby


【解决方案1】:

这称为三元运算符,用作 if/else 语句的一种简写形式。它遵循以下格式

statement_to_evaluate ? true_results_do_this : else_do_this

很多时候这将用于非常短或简单的 if/else 语句。你会看到这种类型的语法是一堆基于 C 的不同语言。

【讨论】:

    【解决方案2】:

    以 ? 结尾的函数在 Ruby 中是只返回布尔值的函数,即 true 或 false。

    When you write a function that can only return true or false, you should end the function name with a question mark.

    您给出的示例显示了一个ternary statement,它是一个单行 if 语句。 .nil? 是一个布尔函数,如果值为 nil,则返回 true,否则返回 false。它首先检查函数是真还是假。然后执行 if/else 来分配值(如果 .nil? 函数返回 true,则将 nil 作为值,否则将 File.join(root_dir, '/') 作为值。

    可以这样改写:

    if root_dir.nil?
      prefix = nil
    else
      prefix = File.join(root_dir, '/')
    end
    

    【讨论】:

    【解决方案3】:

    代码相当于:

    if root_dir.nil? 
      prefix = nil 
    else 
      prefix = File.join(root_dir, '/')
    end
    

    a previous question

    【讨论】:

      猜你喜欢
      • 2012-08-27
      • 2014-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多