Florian Gro<florgro / gmail.com> writes:

> Ruby Quiz wrote:
>
>> 	# metakoans.rb is an arduous set of exercises designed to stretch
>> 	# meta-programming muscle.  the focus is on a single method 'attribute' which
>> 	# behaves much like the built-in 'attr', but whose properties require delving
>> 	# deep into the depths of meta-ruby.
>
> Here we go then.
>
> I have a golfed (8 lines) and a regular solution (21 lines) and
> generally do the simplest thing that makes the tests work.
>
> Got it to run in two tries by the way. I failed the fourtytwo test at
> first. After that everything worked fine. :)

Here's my solution, done in two tries too.  Took about 15 minutes, I
think.


class Module
  def attribute(a, &block)
    if a.kind_of? Hash
      a, default = a.to_a.first
    else
      default = nil
    end

    a = a.to_sym
    ivar = "@#{a}"

    define_method(a) {
      if instance_variables.include? ivar
        instance_variable_get ivar
      else
        block ? instance_eval(&block) : default
      end
    }
    define_method("#{a}=") { |v| instance_variable_set ivar, v }
    define_method("#{a}?") { !!__send__(a) }
  end
end


> And thanks for a great quiz. Being able to do things test first rules!

Yeah, it really was a fun quiz.
-- 
Christian Neukirchen  <chneukirchen / gmail.com>  http://chneukirchen.org