Skip to content

Instantly share code, notes, and snippets.

@erikdstock
Created September 28, 2022 19:34
Show Gist options
  • Save erikdstock/c43f552bc392594f7dc29bc64850680c to your computer and use it in GitHub Desktop.
Save erikdstock/c43f552bc392594f7dc29bc64850680c to your computer and use it in GitHub Desktop.
Ruby hash with js object-like syntax
# Nesting would not work here but could easily be tweaked to do so
# other hash methods that return a copy (eg #merge) also need to be reimplemented
# OpenStruct already does this too btw
class HashObj < SimpleDelegator
def method_missing(method_name, *args, &block)
if __getobj__.keys.include?(method_name)
puts "looking for #{method_name}"
__getobj__[method_name]
else
super
end
end
end
ho = HashObj.new({a: 1, b: 2})
ho.a
# => 1
ho.b
# => 2
ho.c
# => NoMethodError: undefined method `c' for {:a=>1, :b=>2}:HashObj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment