Ruby ? ? Means

Ruby ? ? Means

This article will clarify this line of code; prefix = root_dir.nil? ? nil : File.join(root_dir, '/').

the Usage of prefix = root_dir.nil? ? nil : File.join(root_dir, '/') in Ruby

Two points must be clarified:

  • The root_dir.nil?.
  • The ? ... : ....

The nil? method returns true if variable root_dir is nil and false otherwise.

Beginners may be confused by the ? at the end of the method name. It’s standard practice to end the function name with a question mark when writing a function that can only return true or false.

if root_dir.nil?
  File.join(root_dir, '/')

As we use nil? to check whether a variable is null or not, it’s necessary to end the function with a question mark.

The ? ... : ... is known as ternary operator. It’s a shorthand for the if/else statement.

Related Article - Ruby Operator

  • Not Equal Operator in Ruby
  • Double Colon :: Operator in Ruby
  • The or Operator in Ruby
  • Combined Comparison Operator <=> in Ruby
  • The Binary Left Shift Operator in Ruby