Christian Neukirchen wrote: > 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 > This demonstrates a problem I have with many solutions -- taking Florians as an example. class Test attribute 'a' end tst.a? # => false OK tst.a = false # => false OK tst.a? # => false This should be true Regards, Michael -- Michael Ulm R&D Team ISIS Information Systems Austria tel: +43 2236 27551-219, fax: +43 2236 21081 e-mail: michael.ulm / isis-papyrus.com Visit our Website: www.isis-papyrus.com --------------------------------------------------------------- This e-mail is only intended for the recipient and not legally binding. Unauthorised use, publication, reproduction or disclosure of the content of this e-mail is not permitted. This email has been checked for known viruses, but ISIS accepts no responsibility for malicious or inappropriate content. ---------------------------------------------------------------