0
I’m learning Ruby and I’m having a question about how to make a if
inside the render to display the param
only if he exists...
Ex:
if params[:field]
puts 'field' => params[:field],
end
How do I fix it in this code?
render :json => {
'request'=>{
'negotiation' => params[:negotiation],
'state' => params[:state],
'city' => params[:city],
},
'response'=>lista,
}
abs!
Can you tell me, why I can’t get this hash popular before instating it?
– Ricardo
I don’t understand your doubt.
– Alex Takitani
Because I cannot start by adding "res['request']['negotiation'] = x". Because I need to create the empty hash first?
– Ricardo
Vc can, nothing prevents you from creating a hash res = {} and adding the necessary keys.
– Alex Takitani
That, but why should I create it zeroed first? In PHP for example I don’t need to create a $array = array(), I can start directly with $array['key'] = value.
– Ricardo
You can, but in your case as you want to do if to know which fields will or will not exist, it would not work. But nothing prevents you from declaring a hash like this: h = { 'key' : value }.
– Alex Takitani
I understand your question. It is not possible to initialize as in php, ruby hashes and arrays have to be declared before they can be used.
– Alex Takitani