views:

279

answers:

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

Would a Ruby person laugh at me for writing it this way? It doesn't seem particularly concise like some Ruby code I've seen.

+5  A: 

Nothing really wrong with it as-is, but can be made more concise:

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

Alternatively:

parent_id = if (params[:parent_type] == "Order")
    nil
else
    params[:parent_id]
end
Thom Smith
There's a typo there. The ">" should be a "?"
Martin Owen
I really like the second option. Makes it clear that both options ultimately assign value to parent_id.
nimrodm
The ternary form always assigns a value, unlike the "x = y unless z" form, which leaves x alone if x is already assigned (as does the if-else). So if you want a one-liner that replicates the if-else form, go with the ternary.
zetetic
+3  A: 

I think it's fine the way it is. I'm a Ruby person, and I wouldn't laugh at you for writing it that way. It's clear what the code does and there's no real code duplication, so I wouldn't worry about it.

Chris Bunch
I agree here also...
Joseph Silvashy
+8  A: 

That looks perfectly reasonable to me. You could move the assignment in front of the if ( parent_id = if params...) or use the ternary, but I don't think the result would look better.

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

parent_id = params[:parent_id] unless params[:parent_type] == "Order"
sepp2k
awesome... this is the ruby way to do things, assignment goes in front. this is the reason "unless" was created so we can have the same convention inversely.
Joseph Silvashy
+2  A: 

I like:

parent_id = (params[:parent_type] == "Order" ? nil : params[:parent_id])
dwoolley
+1  A: 

One more variation:

parent_id = (params[:parent_type] == "Order") && params[:parent_id]
not a very expressive way.. quite confusing actually the fact that the logical operator do not only return booleans...
luca