Created
January 16, 2010 06:07
-
-
Save robertsosinski/278682 to your computer and use it in GitHub Desktop.
Metaprogramming example
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 Person | |
def initialize(options = {}) | |
options.each do |key, value| | |
self.instance_variable_set(:"@#{key}", value) | |
self.class.send(:define_method, key) do | |
self.instance_variable_get(:"@#{key}") | |
end | |
self.class.send(:define_method, "#{key}=".intern) do |*args| | |
self.instance_variable_set(:"@#{key}", args.first) | |
end | |
end | |
end | |
end | |
p = Person.new(:first => "alice", :last => "android", :city => "nyc", :state => "state", :lang => "ruby") | |
puts p.first | |
p.first = "bob" | |
puts p.first |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment