Search code examples
rubyhashtable

What does the ? operator do in Ruby


I have a function here that checks to see if the last element of an input array is a hash table. If so, it'll remove the last element in the Hash Table. This is from the solution in Ruby Monk section 6.2.

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

Whats does the '?' operator do between ...(Hash) ? arguments.pop ...

Why is there a ' : {} ' after arguments.pop as well.


Solution

  • It's a ternary conditional operator. It has the following form:

    condition ? true_value : false_value
    

    It evaluates the condition, and assumes the value of true_value when the condition is true, and the false_value when the condition is false.