LoginSignup
12
11

More than 5 years have passed since last update.

[Ruby] Hashのsymbolize_keysをrails抜きで実装する

Posted at

軽く捜しても意外と見つからない思いを何度かしたので、書いておく。

class Hash
  def symbolize_keys
    self.each_with_object({}){|(k,v),memo| memo[k.to_s.to_sym]=v}
  end
  def deep_symbolize_keys
    self.each_with_object({}){|(k,v),memo| memo[k.to_s.to_sym]=(v.is_a?(Hash) ? v.deep_symbolize_keys : v)}
  end
end
h = {'a' => {'b' => 123, 'c' => 789, 123 => 'a'}, 'x' => 123, :foo => 'bar'}
h.symbolize_keys
#=> {:a=>{"b"=>123, "c"=>789, 123=>"a"}, :x=>123, :foo=>"bar"}
h.deep_symbolize_keys
#=> {:a=>{:b=>123, :c=>789, :"123"=>"a"}, :x=>123, :foo=>"bar"}

Railsの実装とは少し違うけど、充分な範囲で。

12
11
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
11