Skip to content

Instantly share code, notes, and snippets.

@sinsoku
Last active August 14, 2017 09:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sinsoku/d3c2eb9128a52dac3442892d7c49284d to your computer and use it in GitHub Desktop.
Save sinsoku/d3c2eb9128a52dac3442892d7c49284d to your computer and use it in GitHub Desktop.
I want to build a nested hash more easily.
# frozen_string_literal: true
module NestedHashBuildable
# Builds a nested hash
#
# NestedHashBuildable.build(:a, :b, c: obj)
# #=> { a: { b: { c: obj } } }
def self.build(*keys, obj)
keys.reverse.inject(obj) { |a, i| { i => a } }
end
def nested_hash(*keys, obj)
NestedHashBuildable.build(*keys, obj)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment