Hi I have a question about ruby on rails
Apparently I have a statement like this:
def sort_column
Product.column_names.include?(params[:sort]) ? params[:sort] : "name"
end
From what I read, it's said that this method sort the column based on params[:sort] and if there no params the products will be sorted by "name". However, I don't understand the way this statement is written, especially the second "?". Can someone explain it to me ?
?:
is a ternary operator that is present in many languages. It has the following syntax:In Ruby, it is a shorter version of this:
This is your code, rearranged for easier understanding.
First question mark is part of a method name, the second one - part of ternary operator (which you should read about).
The first question mark is part of the method name:
include?
.The second question mark and the colon are part of the ternary operand:
(if this is true) ? (do this) : (else, do that).
It means that, if
Product.column_names
containsparams[:sort]
, it will returnparams[:sort]
. Else, it will return"name"
.We must to be careful with the expression part to be evaluated in the ternary operator, for instance when using
and
versus&&
, this is what could happen:That line translates roughly as:
The ? : is a ternary operator; shorthand for a brief if-else.