From: Marnen Laibow-Koser Date: 2010-01-24T12:04:08+09:00 Subject: Re: Writing proper getter in a Ruby way Benoit Daloze wrote: [...] > Now I begin to describe the real code, because abstract examples would > be hard. > Here it is: > > class Variable > attr_accessor :name, :proc > attr_writer :value > > # Create a new Variable, with optional name, value and proc > def initialize(*args, &proc) > args.each do |arg| > case arg > when Numeric then @value = arg > when String, Symbol then @name = arg.to_s > else raise ArgumentError, "..." > end > end > @proc = proc > end This seems a strange use case, but in any event, ou should not be doing this much class checking. I suggest a different approach entirely: pass a hash to the constructor rather like many Rails functions do. So: class Variable attr.accessor :name, :proc attr.writer :value def initialize(options, &proc) @name = options[:name] ? options[:name].to_s : nil @value = options[:value] @proc = proc end > > def value > @value or @proc && @proc.call.value > end > > def to_s > name || 'unnamed_variable' > end > end ...and these can stay the same. Best, -- Marnen Laibow-Koser http://www.marnen.org marnen@marnen.org -- Posted via http://www.ruby-forum.com/.