On Nov 15, 2007 5:48 PM, Suraj Kurapati <snk / gna.org> wrote: > Marc Heiler wrote: > > (By the way, an accessor_read that can query variables with ? on the end > > would be nice in std ruby too... I am not complaining at all, ruby is so > > flexible, I already use this for my code and i love it, like @file.readable? > > that queries a "special" reader accessor... i think it reads nicer than > > @file.readable but this is just my opinion) > > Do you mean that attr_accessor treats symbols with a question mark > differently by creating a "symbol_without_question=" writer method and a > "symbol_with_question" reader method? For example: > > class Foo > attr_acessor :readable? # defines Foo#readable= and Foo#readable? > end > > f = Foo.new > f.readable? #=> nil > f.readable = 99 > f.readable? #=> 99 > > This would be very useful, because it would make the following > workaround obsolete: > > class Foo > attr_writer :readable # only defines Foo#readable= > > def readable? > @readable > end > end > > Oh wishing star, here is another wish for you! :-) > Thanks for your consideration. Here you go (wouldn't use it myself though): class Module # get a unique alias method_name = '__attr_accessor__#{rand(123456789)}__#{Time.now.to_i}' alias_method method_name, :attr_accessor define_method :attr_accessor do |name| name = name.to_s if name[-1] == ?? sname = name[0..-2] attr_writer sname define_method "#{name}" do instance_variable_get "@#{sname}" end else send(method_name, name) end end end class Foo attr_accessor :readable? attr_accessor :bar end f = Foo.new f.readable? # => nil f.readable = 99 # => 99 f.readable? # => 99 f.bar = 42 # => 42 Regards, Sean