Last active
December 10, 2015 15:38
-
-
Save pwightman/4455348 to your computer and use it in GitHub Desktop.
method_missing example of accessing hashes like native objects.
This file contains 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
class JObject | |
def initialize hash | |
@hash = hash | |
end | |
def method_missing(m, *args, &block) | |
m = m.to_s | |
if m.end_with?("=") | |
m = m[0, m.length - 1] | |
@hash[m] = args.first | |
end | |
obj = @hash[m] | |
obj = JObject.new(obj) if obj.is_a?(Hash) | |
obj | |
end | |
end | |
hash = { | |
'foo' => 'bar', | |
'other_foo' => { | |
'hello' => 'world' | |
} | |
} | |
obj = JObject.new(hash) | |
puts obj.foo | |
obj.foo = 'hello' | |
puts obj.foo | |
puts obj.other_foo.hello |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment