Help us understand the problem. What is going on with this article?

[Ruby] 途中にArrayが入っても辿れるdeep_symbolize_keys

More than 5 years have passed since last update.

Railsの実装だと、ハッシュ構造の途中に配列が挟まった場合に、それ以下の階層が処理されないことに気づく。

{'a'=>[{'b'=>100}, {'c'=>999}]}.deep_symbolize_keys
#=> {:a=>[{"b"=>100}, {"c"=>999}]}

これも辿れるものを。

class Hash
  def deep_symbolize_keys
    self.each_with_object({}) do |(key, val), memo|
      if val.is_a?(Array)
        val = val.map{|v| v.deep_symbolize_keys}
      elsif val.is_a?(Hash)
        val = val.deep_symbolize_keys
      end
      memo[key.to_s.to_sym] = val
    end
  end
end
{'a'=>[{'b'=>100}, {'c'=>999}]}.deep_symbolize_keys
#=> {:a=>[{:b=>100}, {:c=>999}]}

今回はRailsの外でオレオレ実装したい場合だったので、これで。Rails上でやりたい場合は大胆に deep_transform_keys から上書きしちゃうか、別名をつけてやるのが良いかと。

nao58
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした