Skip to content

Instantly share code, notes, and snippets.

@PJZ9n
Last active October 4, 2022 20:03
Show Gist options
  • Save PJZ9n/4dc975f1aefa6a991af087131b3b842c to your computer and use it in GitHub Desktop.
Save PJZ9n/4dc975f1aefa6a991af087131b3b842c to your computer and use it in GitHub Desktop.
ドット区切り文字列がキーのハッシュを連想ハッシュに変換する
hash_input = {"a.b" => "value", "a.c" => "hoge", "b.1" => "a", "a.b.c" => "aa"}
hash_output = {}
ENABLE_OVERRIDE = true
hash_input.each do |key, value|
key_splits = key.split(".")
current_hash = hash_output
key_splits_tmp = key_splits.dup
key_splits_tmp.delete_at(key_splits.size - 1) # remove last value
key_splits_tmp.each do |key_split|
current_hash[key_split] = {} if current_hash[key_split].nil?
current_hash[key_split] = {} if ENABLE_OVERRIDE && !current_hash[key_split].kind_of?(Hash)
current_hash = current_hash[key_split]
end
next unless ENABLE_OVERRIDE || current_hash.kind_of?(Hash) # no override
current_hash[key_splits.last] = value
end
p hash_output
# {"a"=>{"b"=>{"c"=>"aa"}, "c"=>"hoge"}, "b"=>{"1"=>"a"}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment