Ruby中的独立问号有什么作用?

Use*_*159 0 ruby

可能重复:
如何在Ruby中使用条件运算符(?:)?

我正在教自己Ruby并经历RubyMonk练习.我遇到了这个令我困惑的代码:

def calculate(*arguments)
  options = arguments[-1].is_a?(Hash) ? arguments.pop : {}
  options[:add] = true if options.empty?
  return add(*arguments) if options[:add]
  return subtract(*arguments) if options[:subtract]
end
Run Code Online (Sandbox Code Playgroud)

请注意,加法和减法是添加/减去其参数的现有函数,其长度可能不同.

计算应该像这样工作

 calculate(1,2,3,4,5,add: true) => 10
 calculate(10,3,4, subtract: true) => 3
Run Code Online (Sandbox Code Playgroud)

我的问题是,有人可以解释行中发生的事情:

options = arguments[-1].is_a?(Hash) ? arguments.pop : {}
Run Code Online (Sandbox Code Playgroud)

也就是说,独立问号到底是做什么的?此外,结肠是做什么的?

非常感谢你的帮助!

Joh*_*ohn 6

options = arguments[-1].is_a?(Hash) ? arguments.pop : {}
Run Code Online (Sandbox Code Playgroud)

是三元运算符声明的一部分.这是一种在单行上进行if条件的方法.

(condition) ? then : else.
Run Code Online (Sandbox Code Playgroud)