benoitr
benoitr

Reputation: 6105

Get the key/value pairs of a nested hash

Please see the following hash:

params[:category] #=> {"category"=>{"name"=>"name1", "parent_id"=>1, "category"=>{"name"=>"name2"}}}

and the desired output :

params[:category] #=> {"category"=>{"name"=>"name1", "parent_id"=>1 }}

I've tried several things but none succeed

params[:category].delete(params[:category][...]

How can I get the key/value pairs of this nested hash in order to delete it?

Thanks for your help

Upvotes: 2

Views: 1233

Answers (3)

jizak
jizak

Reputation: 382

h = {"category"=>{"name"=>"name1", "parent_id"=>1, "category"=>{"name"=>"name2"}}}
h['category'].delete('category')
{"category"=>{"name"=>"name1", "parent_id"=>1}}

Third line is the result. Did you want to delete category key of h['category']?

Upvotes: 0

ted
ted

Reputation: 5329

If the hash is:

params[:category] = {"category"=>{"name"=>"name1", "parent_id"=>1, "category"=>{"name"=>"name2"}}}

Then use:

params[:category]["category"].slice!("category")

Upvotes: 0

the Tin Man
the Tin Man

Reputation: 160631

If the hash is:

params[:category] = {"category"=>{"name"=>"name1", "parent_id"=>1, "category"=>{"name"=>"name2"}}}

Then use:

params[:category]['category'].delete('category')
params[:category]
=> {"category"=>{"name"=>"name1", "parent_id"=>1}}

Upvotes: 4

Related Questions