question mark and colon - if else in ruby

2019-04-25 10:57发布

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 ?

5条回答
孤傲高冷的网名
2楼-- · 2019-04-25 11:14

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

expression ? value_if_true : value_if_false

In Ruby, it is a shorter version of this:

if expression
  value_if_true
else
  value_if_false
end
查看更多
萌系小妹纸
3楼-- · 2019-04-25 11:15

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).

查看更多
Bombasti
4楼-- · 2019-04-25 11:19
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 the colon are part of the ternary operand: (if this is true) ? (do this) : (else, do that).

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

查看更多
放荡不羁爱自由
5楼-- · 2019-04-25 11:20

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:

2.6.2 :014 > a = false
 => false
2.6.2 :015 > b = true
 => true
2.6.2 :016 > a and b ? 'first' : 'second'
 => false
2.6.2 :017 > a && b ? 'first' : 'second'
 => "second"
2.6.2 :018 > (a and b) ? 'first' : 'second'
 => "second"
查看更多
男人必须洒脱
6楼-- · 2019-04-25 11:28

That line translates roughly as:

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

The ? : is a ternary operator; shorthand for a brief if-else.

查看更多
登录 后发表回答