Created
June 22, 2010 08:00
-
-
Save rklemme/448155 to your computer and use it in GitHub Desktop.
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 Module | |
def attr_with_default(name, default = nil, &init) | |
n = "@#{name}" | |
define_method name do | |
instance_variable_get(n) || (init ? init.call(self) : default) | |
end | |
attr_writer name | |
end | |
end | |
class Foo | |
attr_with_default "bar", 123 | |
attr_with_default "baz" do |obj| obj.object_id end | |
end | |
f = Foo.new | |
printf "%-10s %p\n", 'bar', f.bar | |
f.bar = 99 | |
printf "%-10s %p\n", 'bar', f.bar | |
printf "%-10s %p\n", 'baz', f.baz | |
f.baz = 11 | |
printf "%-10s %p\n", 'baz', f.baz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment