0

Possible Duplicate:
How do I use the conditional operator (? :) in Ruby?

I'm teaching myself Ruby and going through the RubyMonk exercises. I came across this code, which confuses me:

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

Note that add and subtract are existing functions that add/subtract its arguments, which could vary in length.

Calculate is supposed to work like this

 calculate(1,2,3,4,5,add: true) => 10
 calculate(10,3,4, subtract: true) => 3

My question is can someone explain what is happening in the line:

options = arguments[-1].is_a?(Hash) ? arguments.pop : {}

Namely, what exactly does a standalone question mark do? Also, what does the colon do?

Thanks a lot for your help!

1

2 Answers 2

6
options = arguments[-1].is_a?(Hash) ? arguments.pop : {}

Is part of a ternary operator statement. It is a way to do an if conditional on a single line.

(condition) ? then : else.
1
  • Thanks, that makes perfect sense.
    – User314159
    Jan 6, 2013 at 3:16
3

It's an alternative way to express if-then-else. For example

options = arguments[-1].is_a?(Hash) ? arguments.pop : {}

is exactly the same as

if arguments[-1].is_a?(Hash)
  options = arguments.pop
else
  options = {}
end
1
  • This was also a helpful comment. Thanks.
    – User314159
    Jan 6, 2013 at 3:17

Not the answer you're looking for? Browse other questions tagged or ask your own question.