Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

question mark and colon - if else in ruby

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 ?

like image 887
u19964 Avatar asked Jun 25 '12 14:06

u19964


People also ask

What does the :: mean in Ruby?

The :: is a unary operator that allows: constants, instance methods and class methods defined within a class or module, to be accessed from anywhere outside the class or module. Remember in Ruby, classes and methods may be considered constants too.

What does question mark mean in Ruby?

What is the question mark in Ruby? It is a code style convention; it indicates that a method returns a boolean value (true or false) or an object to indicate a true value (or “truthy” value). The question mark is a valid character at the end of a method name.

How do I use a question mark in Ruby?

The question mark is used when the method returns boolean value. From the previous examples, it's obvious that the question mark (?) at the end of the method is set when we have a method that returns boolean value — 'true' or 'false'.

How do you use the conditional operator in Ruby?

Conditionals are formed using a combination of if statements and comparison and logical operators (<, >, <=, >=, ==, != , &&, ||) . They are basic logical structures that are defined with the reserved words if , else , elsif , and end .


1 Answers

This is your code, rearranged for easier understanding.

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

First question mark is part of a method name, the second one - part of ternary operator (which you should read about).

like image 86
Sergio Tulentsev Avatar answered Oct 04 '22 03:10

Sergio Tulentsev