Skip to content

Instantly share code, notes, and snippets.

@pwightman
Last active December 10, 2015 15:38
Show Gist options
  • Save pwightman/4455348 to your computer and use it in GitHub Desktop.
Save pwightman/4455348 to your computer and use it in GitHub Desktop.
method_missing example of accessing hashes like native objects.
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