Question mark and colon - if still in ruby

Hi, I have a question about ruby ​​on rails

Apparently I have an instruction like this:

def sort_column Product.column_names.include?(params[:sort]) ? params[:sort] : "name" end 

From what I read, he said that this method sorts the column based on params [: sort], and if there are no parameters, the products will be sorted by "name". However, I do not understand how this expression is written, especially the second "?". Can someone explain this to me?

+6
source share
4 answers

This is your code rebuilt for easier understanding.

 def sort_column cond = Product.column_names.include?(params[:sort]) cond ? params[:sort] : "name" # it equivalent to this # if cond # params[:sort] # else # 'name' # end end 

The first question mark is part of the method name, the second is part of the triple operator (which you should read about).

+14
source

?: is a ternary operator that is present in many languages. It has the following syntax:

 expression ? value_if_true : value_if_false 

In Ruby, this is a shorter version:

 if expression value_if_true else value_if_false end 
+10
source

This line looks something like this:

 if Product.column_names.include?(params[:sort]) params[:sort] else "name" end 

What ?: is a ternary operator; short for short if-else.

+4
source
 Product.column_names.include?(params[:sort]) ? params[:sort] : "name" 

The first question mark is part of the method name: include? .

The second question mark and colon are part of the ternary operand: (if this is true) ? (do this) : (else, do that). (if this is true) ? (do this) : (else, do that).

This means that if Product.column_names contains params[:sort] , it will return params[:sort] . Otherwise, it will return "name" .

+2
source

Source: https://habr.com/ru/post/918950/


All Articles