My solution follows - I think it's pretty straightforward. 16 lines
without golf. The only part I don't really like is the a_init_
sentinel I had to add to pass Koan9. I messed around with redefining
the initializer in the call to a=, but I couldn't get that to work
right.
One thing I noted: I could get through koans 1-5 with a `def a; 42; end` :)
class Object
def attribute name, &block
init_proc = proc {nil}
if block_given?
init_proc = block
elsif name.kind_of? Hash
v = name.values.first
name = name.keys.first
init_proc = proc{v}
end
self.send(:define_method, "#{name}_init_", init_proc)
self.class_eval "def #{name}; if !@#{name}&&!@#{name}_init_ then
@#{name}=#{name}_init_; @#{name}_init_=true; end; @#{name}; end"
self.class_eval "def #{name}?; !(self.#{name}.nil?); end"
self.class_eval "def #{name}=(v); @#{name}=v; end"
end
end
-Adam