What is the more idiomatic ruby ​​way to write this?

if params[:parent_type] == "Order" parent_id = nil else parent_id = params[:parent_id] end 

Will a Ruby man laugh at me to write it like this? This does not seem particularly concise, like some kind of Ruby code that I saw.

+4
source share
6 answers

It looks quite reasonable to me. You can parent_id = if params... move the assignment before if ( parent_id = if params... ) or use a triple, but I don't think the result will look better.

If parent_id is nil or undefined before this line, you can simply write:

 parent_id = params[:parent_id] unless params[:parent_type] == "Order" 
+9
source

There is nothing wrong with this, but can be made more concise:

 parent_id = (params[:parent_type] == "Order") ? nil : params[:parent_id] 

As an alternative:

 parent_id = if (params[:parent_type] == "Order") nil else params[:parent_id] end 
+7
source

I think all is well. I am Ruby's man, and I would not laugh at you for writing it like this. This is clear what the code does, and there is no real duplication of code, so I would not worry about that.

+5
source

I like:

  parent_id = (params [: parent_type] == "Order"? nil: params [: parent_id]) 
+2
source

Another change:

 parent_id = (params[:parent_type] == "Order") && params[:parent_id] 
+1
source

We can use the ternary operator Ruby. Something like that:

 parent_id = params[:parent_type] == "Order" ? nil : params[:parent_id] 

If parent_id is set with nil value, we can write if syntax:

 parent_id = params[:parent_id] unless params[:parent_type] == "Order" 

Or write simple Ruby if-else differently, as you did:

 parent_id = if (params[:parent_type] == "Order") nil else params[:parent_id] end 

For a more Idiomatic Ruby coding method, I found an amazing article about this.

0
source

All Articles