I would like to strip whitespaces from my hash, so if I have
{"my hash key": 12}
I would like to get
{"myhashkey": 12}
I have found some ways to strip from the values, but got a problem to do that on keys. When I tried
my_hash.each_key{|k| k.gsub!(' ', '')}
I got the error:
RuntimeError: can't modify frozen String
and if use only gsub (without '!') it runs fine, but doesn't work.
So what's the best way to achieve that? Thanks!
Keys in the hashes are frozen (as the error message says,) and hence they cannot be modified inplace. The new hash must be constructed with new keys:
{"my hash key" => 12}.map { |k, v| [k.delete(' '), v] }.to_h
#⇒ {"myhashkey"=>12}
NB! there is a pitfall: you might lose some values!
{"a b c" => 42, "abc" => :foo}.
map { |k, v| [k.delete(' '), v] }.to_h
#⇒ {"abc"=>:foo}
You could use transform_keys:
my_hash = { 'my hash key': 12 }
#=> {:"my hash key"=>12}
my_hash.transform_keys { |k| k.to_s.delete(' ').to_sym }
#=> {:myhashkey=>12}
The to_s / to_sym conversion is needed because Symbol doesn't implement delete. You can omit it if your keys are actually strings:
my_hash = { 'my hash key' => 12 }
#=> {:"my hash key"=>12}
my_hash.transform_keys { |k| k.delete(' ') }
#=> {:myhashkey=>12}
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