Saturday 15 June 2013

Inserting an entry in Ruby hash at specific position -


Seeing a hash with a nested hash in it:

  hash = {" Some_key "= & gt; "Value", "Nested" = & gt; {"Key1" = & gt; "Well 1", "Key2" = & gt; "Val2"}}   

and the path to a key in the string format:

  path = "nested .key2"   

How can I add a new key-value pair before to key 2 entry? Therefore, the expected output should be:

  hash = {"some_key" => "Value", "Nested" = & gt; {"Key1" = & gt; "Val1", "new_key" = & gt; "New_value"}, "key2" = & gt; "Val2"}}   

edit

My goal is to add a type of label before some key In order to change the value / value added with jamal comment to dump the hash as a valid text and post process, the text AAAIIM, YAML is programmatically no other way to add comments before the specific key.

It is easy to represent the array of hashes:

  Subhash = hash ['nested']. To_a insert_at = subhash.index (sahash.SOSOC ('key2') hash ['nested'] = hash [Subhash.insert (insert_at, ['new_key', 'new_value']]]   

This can be wrapped in a function:

  class hash def (key, kvpar) arr = to_a pos = arr.index (arr.assoc (key)) if arr arr .insert (pos, kvpair) else arr & lt; & Lt; # ("Key2", ['new_key', 'new_value']) P hash # {"some_key" => "Value", "Nested" = Already changes the hash [AR] and end hash ['nested']. & Gt; {"Key1" = & gt; "Val1", "new_key" = & gt; "New_value", "key2" = & gt; "Val2"}}    

No comments:

Post a Comment