conditional variable assignment from array

J

Josselin

one of my methods receives a sort parameter either as

params => {"sort"=>{"criteria"=>"1"} }
OR
params => {"sort"=>"1"}

presently, I assign a variable @sc as follows :

params[:sort].nil? ? @sc = "1" : @sc = params[:sort][:criteria]

how can I assign @sc to params[:sort][:criteria] OR params[:sort]
whatever received... ?

tfyh

joss
 
P

Peter Szinek

Josselin said:
one of my methods receives a sort parameter either as

params => {"sort"=>{"criteria"=>"1"} }
OR
params => {"sort"=>"1"}

presently, I assign a variable @sc as follows :

params[:sort].nil? ? @sc = "1" : @sc = params[:sort][:criteria]

how can I assign @sc to params[:sort][:criteria] OR params[:sort]
whatever received... ?

You could try something like

stuff = params[:sort]
@sc = stuff.is_a? String ? stuff : stuff[:criteria] unless stuff == nil

Maybe I did not understand your question properly, if this does not seem
to work, please try to elaborate...

Peter

__
http://www.rubyrailways.com
 
R

Robert Klemme

one of my methods receives a sort parameter either as

params => {"sort"=>{"criteria"=>"1"} }
OR
params => {"sort"=>"1"}

presently, I assign a variable @sc as follows :

params[:sort].nil? ? @sc = "1" : @sc = params[:sort][:criteria]

how can I assign @sc to params[:sort][:criteria] OR params[:sort]
whatever received... ?

First of all you cannot mix symbol and string keys, i.e. you cannot use
a symbol to retrieve a string key:

irb(main):001:0> h={"sort"=>1}
=> {"sort"=>1}
irb(main):002:0> h[:sort]
=> nil

Maybe you want something like this:

tmp = params["sort"]
@sc = Hash === tmp ? tmp["criteria"] : tmp

Cheers

robert
 
W

William James

Josselin said:
one of my methods receives a sort parameter either as

params => {"sort"=>{"criteria"=>"1"} }
OR
params => {"sort"=>"1"}

presently, I assign a variable @sc as follows :

params[:sort].nil? ? @sc = "1" : @sc = params[:sort][:criteria]

how can I assign @sc to params[:sort][:criteria] OR params[:sort]
whatever received... ?

tfyh

joss

h = {"sort"=>{"criteria"=>{"criterion"=>{"foo"=>"1"}}}}
# Get the innermost value.
while (h = h.to_a.flatten.last).class == Hash do end
p h
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top