Last active
September 7, 2018 14:03
-
-
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
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
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" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this! Useful.