Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One-line assignment: If (condition) variable = value1 else value2

How do I do something like this?

if params[:property] == nil 
 @item.property = true
else 
 @item.property = false

Always forget the proper syntax to write it in one line.

In PHP it would be like this:

@item.property=(params[:property]==nil)true:false

Is it the same in rails?

like image 402
user1885058 Avatar asked Dec 08 '12 11:12

user1885058


1 Answers

use the ternary operator:

@item.property = params[:property] ? true : false

or force a boolean conversion ("not not" operation) :

@item.property = !!params[:property]

note : in ruby, it is a common idiom not to use true booleans, as any object other than false or nil evaluates to true.

like image 64
m_x Avatar answered Nov 03 '22 00:11

m_x