Iterating hashes and assigning corresponding values in ruby

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.

ruby rails wrote in post #1143483:

How can I achieve it. Please help.

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

h=(1…10).each_with_object( {} ) { |no,h|
k,v=“key#{no}”, “value#{no}”
h[params[k]] = params[v] if params[k] && params[v]
}

p h
{“business”=>“shoes”, “date”=>“2014”, “price”=>“3000”}

Regis d’Aubarede wrote in post #1143489:

ruby rails wrote in post #1143483:

How can I achieve it. Please help.

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

h=(1…10).each_with_object( {} ) { |no,h|
k,v=“key#{no}”, “value#{no}”
h[params[k]] = params[v] if params[k] && params[v]
}

p h
{“business”=>“shoes”, “date”=>“2014”, “price”=>“3000”}

or

h=params.keys.grep(/^key/).each_with_object({}) { |k,h|
h[params[k]]=params[“value#{k[3…-1]}”]
}

Thanks Regis d’Aubarede… It worked… You are great… :slight_smile:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs