views:

282

answers:

5

With Ruby, how can I set a variable based on a condition? Something like:

dog_name = params[:dog][:name] if params[:dog]

And then dog_name just wouldn't be set if params[:dog] wasn't set.

Right now I'm getting an error if params[:dog] is nil.

A: 

How about:

dog_name = params[:dog][:name] if params.has_key?(:dog) && params[:dog].has_key(:name)

What error are you getting when params[:dog] is nil?

ChrisInEdmonton
+4  A: 

You could use the && operator:

dog_name = params[:dog] && params[:dog][:name]

So now dog_name will be nil if params[:dog] does not exist, else it will be the value of params[:dog][:name].

yjerem
A: 

You also could use the &&= operator:

dog_name = params.has_key(:dog)
dog_name &&= params[:dog].has_key(:name)
dog_name &&= params[:dog][:name]
marocchino
A: 

How about:

dog_name = params[:dog][:name] unless params[:dog].nil?

Sujal

sujal
+2  A: 

What you're doing should work.

I imagine that params[:dog] is not actually nil. I bet it's an empty string (or empty hash). (You can check on this by outputting params[:dog].inspect to the log or stdout.)

Rails has a method blank? that tests for nil, empty string, empty collection.

Try:

dog_name = params[:dog][:name] if !params[:dog].blank?

Or:

dog_name = params[:dog][:name] unless params[:dog].blank?
Luke Francl