Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what does ? ? mean in ruby [duplicate]

What does the line below checks and perform?

prefix = root_dir.nil? ? nil : File.join(root_dir, '/')

Here is the block that contains the line of code.

def some_name(root_dir = nil, environment = 'stage', branch)
        prefix = root_dir.nil? ? nil : File.join(root_dir, '/')
.
.
. 

i know that the '?' in ruby is something that checks the yes/no fulfillment. But I am not very clear on its usage/syntax in the above block of code.

like image 681
OK999 Avatar asked Aug 05 '26 00:08

OK999


2 Answers

Functions that end with ? in Ruby are functions that only return a boolean, that is, true, or false.

When you write a function that can only return true or false, you should end the function name with a question mark.

The example you gave shows a ternary statement, which is a one-line if-statement. .nil? is a boolean function that returns true if the value is nil and false if it is not. It first checks if the function is true, or false. Then performs an if/else to assign the value (if the .nil? function returns true, it gets nil as value, else it gets the File.join(root_dir, '/') as value.

It can be rewritten like so:

if root_dir.nil?
  prefix = nil
else
  prefix = File.join(root_dir, '/')
end
like image 136
Amnesthesia Avatar answered Aug 06 '26 13:08

Amnesthesia


This is called a ternary operator and is used as a type of shorthands for if/else statements. It follows the following format

statement_to_evaluate ? true_results_do_this : else_do_this

A lot of times this will be used for very short or simple if/else statements. You will see this type of syntax is a bunch of different languages that are based on C.

like image 33
tykowale Avatar answered Aug 06 '26 14:08

tykowale