Created
September 28, 2022 19:34
-
-
Save erikdstock/c43f552bc392594f7dc29bc64850680c to your computer and use it in GitHub Desktop.
Ruby hash with js object-like syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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