Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - update hash keys to strip whitespaces

Tags:

ruby

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!

like image 487
Ronan Lopes Avatar asked Jun 28 '26 09:06

Ronan Lopes


2 Answers

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}
like image 120
Aleksei Matiushkin Avatar answered Jun 30 '26 23:06

Aleksei Matiushkin


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}
like image 41
Stefan Avatar answered Jun 30 '26 23:06

Stefan