Skip to content

Instantly share code, notes, and snippets.

@zhuravel
Last active December 19, 2015 01:59
Show Gist options
  • Save zhuravel/5879620 to your computer and use it in GitHub Desktop.
Save zhuravel/5879620 to your computer and use it in GitHub Desktop.
# Hash with getters and setters #
#################################
Hash.class_eval do
def method_missing(m, *a)
m.to_s =~ /=$/ ? self[$`] = a[0] : a == [] ? self[m.to_s] : super
end
end
hsh = {}
hsh.test1 = "one"
hsh.test2 = "two"
hsh # {"test1"=>"one", "test2"=>"two"}
hsh.test1 # "one"
# Recursive hash #
##################
class RecursiveHash < ::Hash
def initialize
super { |hash, key| hash[key] = RecursiveHash.new }
end
end
hsh = RecursiveHash.new
hsh[:one][:two][:three] = "no error!"
hsh # {:one=>{:two=>{:three=>"no error!"}}}
hsh[:one] # {:two=>{:three=>"no error!"}}
hsh[:one][:two][:three] # "no error!"
hsh[:batman] # {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment