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.
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', ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With