replace space with underscore in Keys for a Hash

1.4k Views Asked by At

I have a hash in which Keys have some spaces like shown below. I want to replace the space with underscores. I don't know why but the program below isn't working.

Keys: "VoLTE QCI1 Setup Failure%" "VoLTE QCI1 Setup Failures" "VoLTE QCI1 Setup Attempts"

@@parsed_items.each_key {|key|
key.gsub(/\s/,'_')
ap key
    }

Expected Output: "VoLTE_QCI1_Setup_Failure%" "VoLTE_QCI1_Setup_Failures" "VoLTE_QCI1_Setup_Attempts"

Current Output: "VoLTE QCI1 Setup Failure%" "VoLTE QCI1 Setup Failures" "VoLTE QCI1 Setup Attempts"

1

There are 1 best solutions below

3
On BEST ANSWER

If you want to re-key your whole hash, you might have to rebuild it:

@@parsed_items = Hash[
 @@parsed_items.map do |key, value|
   [ key.gsub(/\s/,'_'), value ]
 end
]

The each_key method ignores whatever your block returns, it just throws it out, so no alterations are made to the hash itself.

You could also write a helper method to de-underscore arbitrary hashes that does this as well.

Note that using @@ class-level variables is often a sign of mixed concerns. Instance methods should not be poking around in class data, it's supposed to be considered private. If you do need access to it, expose class-level methods that give you a clean interface.