Meaning of Ruby Question Mark ?

Stewart Nguyen Feb 02, 2024
Meaning of Ruby Question Mark ?

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?
  nil
else
  File.join(root_dir, '/')
end

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