From: Benoit Daloze Date: 2010-01-24T23:11:17+09:00 Subject: Re: Writing proper getter in a Ruby way 2010/1/24 Marnen Laibow-Koser : > 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. > Thank you for your answer. I know that class checking is not so OO. The old behavior was like you propose: using a Hash. and then we were using @name, @value = options.values_at(:name, :value) # values_at is really nice here :) That's a very cool approach except it's really longer and I think it's significant in this context. We are writing a math library, this class represent a mathematical variable, so here we have: x = var :x, 3 # with my way x = var name: :x, value: 3 # with hash, in 1.9 x = var :name => :x, :value => 3 # with hash, in 1.8 (not relevant) To specify the name is already redundant with the real var name. It's possible via caller to get it, with parsing, but that's not a very good way neither. (Would you support that?) So much checking in a case statement for classes looks bad, but it was intended to raise an ArgumentError if we still used the old behavior. So, could I have your opinion, if we forget about Hash because it looks too long here ? Thank you for your answer again.