3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Hashのkeyをflatにする

Posted at

何階層にも入れ子になっているHashのKeyを'_'で結合してフラットにします。

#!/usr/bin/env ruby

require "awesome_print"

def flatten_key(hash, key = "", result = {})
  hash.each do |k, v|
    k2 = "#{key} #{k}"

    if v.is_a?(Hash)
      flatten_key(v, k2, result)
    else
      result[k2.strip.gsub(" ", "_").to_sym] = v
    end
  end

  result
end


ap flatten_key(
  {
    studio3104: { sex: "male", age: "young", favorite: { tsukemen: "warito", sushi: "any" } },
    kenjiskywalker: { sex: "male", age: "ojisan", },
  }
)
{
                  :studio3104_sex => "male",
                  :studio3104_age => "young",
    :studio3104_favorite_tsukemen => "warito",
       :studio3104_favorite_sushi => "any",
              :kenjiskywalker_sex => "male",
              :kenjiskywalker_age => "ojisan"
}
3
2
0

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?