Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an entry in hash at certain position

Tags:

ruby

hash

Given a hash:

{"set_filter"=>["0"], "test1"=>["=test1"], "test2"=>["=test2"]}

how can I add a new key-value pair after the set_filter entry? The expected output should be something like this:

{
  "set_filter" => ["0"],
  "test3" => ["=test3"],
  "test1" => ["=test1"],
  "test2" => ["=test2"]
}

I want to insert a new key-value pair at a certain position in a hash.

like image 391
Ani Avatar asked Feb 20 '16 07:02

Ani


1 Answers

The only order hashes provide is order of insertion, and that only affects iteration. So you can't really add after a specific element, unless you're willing to remove all those following it, insert, and then insert all those back again.

Instead, you might want to use an array of pairs, like this:

A = [["set_filter", "0"], ...]

and then use Array#insert, like this

A.insert(2, ["test3", "=test3"])

When order matters, use the array. When you need a hash interface, you can do

A.to_h # yields { 'set_filter' => '0', ... }
like image 158
Yam Marcovic Avatar answered Nov 15 '22 03:11

Yam Marcovic