Gavin Kistner
5/9/2007 10:36:00 PM
On May 9, 2:10 pm, Markus Hohenhaus <mark...@hni.upb.de> wrote:
> That's it!! Thanks. Now everything works as expected. Allthough I like
> mine better, seems more
> logical to me ;).
Well, you can do that too, if you like:
class Module
def attr_readwrite( *methods )
class_eval{
methods.each{ |method_name|
define_method( method_name ){ |*val|
val = val.first
unless val.nil?
instance_variable_set( "@#{method_name}", val )
else
instance_variable_get( "@#{method_name}" )
end
}
}
}
end
end
class Foo
attr_readwrite :foo, :bar
end
f = Foo.new
f.foo( 42 )
p f.foo
#=> 42
f.foo( 12 )
p f.foo
#=> 12
(I think there's a more elegant way to define the method and detect if
it received a value, but I was too lazy to figure it out.)
I'm pretty sure Ara T. Howard's 'attributes' gem also gives you the
ability to do what you want, where calling the method without a
parameter acts as a getter, and calling it with a parameter acts as a
setter. And I bet his way is clean. :)