6

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?

2
  • That's not valid PHP code, is it? That statement looks like this afaik: $item->property = ($something === NULL) ? true : false Commented Dec 8, 2012 at 12:33
  • maybe, that's just an example Commented Dec 8, 2012 at 13:19

2 Answers 2

17

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.

Sign up to request clarification or add additional context in comments.

Comments

0

m_x answer is perfect but you may be interested to know other ways to do it, which may look better in other circumstances:

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

or

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.