问号和冒号-如果还有红宝石 [英] question mark and colon - if else in ruby
本文介绍了问号和冒号-如果还有红宝石的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关于轨道上的红宝石的问题
Hi I have a question about ruby on rails
显然我有这样的声明:
def sort_column
Product.column_names.include?(params[:sort]) ? params[:sort] : "name"
end
从我的读物来看该方法基于params [:sort]对列进行排序,如果没有params,则产品将按名称进行排序。但是,我不理解该语句的编写方式,尤其是第二个?。有人可以向我解释吗?
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 ?
推荐答案
这是您的代码,已重新排列以便于理解。
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).
这篇关于问号和冒号-如果还有红宝石的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文