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.
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.
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?
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]
.
You also could use the &&= operator:
dog_name = params.has_key(:dog)
dog_name &&= params[:dog].has_key(:name)
dog_name &&= params[:dog][:name]
How about:
dog_name = params[:dog][:name] unless params[:dog].nil?
Sujal
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?