Skip to content

Instantly share code, notes, and snippets.

@glpunk
Last active September 7, 2018 14:03
Show Gist options
  • Save glpunk/7ff56fac4236b6ac5f69 to your computer and use it in GitHub Desktop.
Save glpunk/7ff56fac4236b6ac5f69 to your computer and use it in GitHub Desktop.
getter and setter through method_missing to manipulate a hash inside a ruby class #ruby
class Test
def initialize
@hash = {prop1: 'prop 1 value', prop2: 'prop2 value'}
end
def method_missing(m, *args)
#setter
if /^(\w+)=$/ =~ m
@hash[:"#{$1}"] = args[0]
end
#getter
@hash[:"#{m}"]
end
end
t = Test.new
p t.prop1
p t.prop2
p t.prop3
t.prop3 = 'prop3 value'
p t.prop3
t.prop3 = 'prop3 new value'
p t.prop3
#result:
#"prop1 value"
#"prop2 value"
#nil
#"prop3 value"
#"prop3 new value"
@WontSeeMeComin
Copy link

Thank you for this! Useful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment