Skip to content

Instantly share code, notes, and snippets.

@robertsosinski
Created January 16, 2010 06:07
Show Gist options
  • Save robertsosinski/278682 to your computer and use it in GitHub Desktop.
Save robertsosinski/278682 to your computer and use it in GitHub Desktop.
Metaprogramming example
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