Ruby hashes iterations and assigning corresponding values

Hi,

I have a Shops controller where I am getting params of shop as a hash.
The
params format is

  • {“key1”=>“business”, “value1”=>“shoes”, “key2”=>“date”,
    “value2”=>“2014”, “key3”=>“price”, “value3”=>“3000”}*

In routes file I have written as

  • match
    ‘/shops/:shop_id/new/:key1/:value1/:key2/:value2/:key3/:value3’,
    :to => ‘shops#new’*

So in the browser I will type as

  • localhost:3000/shops/3/new/business/shoes/date/2014/price/3000*

The order of params will not be of same order sometimes. So in the url
it
can be like

  • localhost:3000/shops/3/new/business/shoes/price/3000/date/2014*

so that it should retrive corresponding params and assign the values.

So I need to check the corresponding keys and assign values accordingly.
That means for eg:

  • If params[:key] contains business then value should be assigned as
    “shoes”, if params[:key] is date, then value should be assigned to
    “2014”.etc*

How can I achieve it. Please help.

On 18 April 2014 12:23, prabhu [email protected] wrote:

How can I achieve it. Please help.

I find it much easier to use the url format ?price=3000&date=2014 then
it will all happen for you automatically.

Colin

On Friday, 18 April 2014 07:23:18 UTC-4, prabhu wrote:

In routes file I have written as
The order of params will not be of same order sometimes. So in the url it
“shoes”, if params[:key] is date, then value should be assigned to
“2014”.etc*

How can I achieve it. Please help.

As Colin indicated, you probably shouldn’t do this - there’s already a
standard way to pass a hash of named parameters to a web endpoint.

If you’re stuck with this weird URI format, this should work:

hash_params = {}
hash_params[params[:key1]] = params[:value1]
hash_params[params[:key2]] = params[:value2]
hash_params[params[:key3]] = params[:value3]

But seriously, use query parameters if at all possible. Using route
params
like this means that you’re forced to pass exactly three parameters and
means you’re going to be stuck encoding on the client-side into this
format, instead of using the built-in stuff for submitting forms…

–Matt J.