2

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.

OK999
  • 1,353
  • 2
  • 19
  • 39
  • 2
    One question mark is part of a method name, the other is part of a ternary. – Dave Newton May 04 '15 at 23:29
  • 1
    Here it is in a format you may understand (this pseudo code by the way). `if root_dir == nil { return nil } else { return File.join(root_dir, '/')`. Then get the what is returned by the conditional and assign it to the variable `prefix`. – Rog May 04 '15 at 23:35

3 Answers3

7

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
Community
  • 1
  • 1
  • So, i passed the values as 'some_name(root_dir = . , dev , dev)' , i.e present working dir, dev environment and dev branch. Then, the prefix will be as 'prefix = File.join(. , '/')'.. does this mean the full path is './/', notice the 2 slashes. This is as per http://stackoverflow.com/questions/4114480/when-is-file-join-useful – OK999 May 05 '15 at 17:34
  • I assume '.' and 'dev', 'dev' are strings, and no, it will end up with only a single slash. However, that doesn't matter -- [multiple consecutive slashes in a path will be treated the same way as a single slash](http://unix.stackexchange.com/questions/1910/how-does-linux-handle-multiple-consecutive-path-separators-home-username#comment237535_1919). – Amnesthesia May 05 '15 at 21:34
2

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.

tykowale
  • 449
  • 3
  • 13
1

The code is the equivalent of:

if root_dir.nil? 
  prefix = nil 
else 
  prefix = File.join(root_dir, '/')
end

See a previous question

Community
  • 1
  • 1
roob
  • 1,116
  • 7
  • 11