"ahoward" <ahoward / fsl.noaa.gov> schrieb im Newsbeitrag
news:Pine.LNX.4.53.0305082058130.9618 / eli.fsl.noaa.gov...
>
>
> rubyists-
>
> when implementing the state pattern/factory in ruby, i have used
delegation
> before (require 'delegate') and this works well.  however, it seem like
> something like this can work just as well - with faster execution
times - for
> simple cases:
>
>   module M
>     class << self
>       def new args
> if ...
>   return A.new
> elsif ...
>   return B.new
> else
>   return C.new
> end
>       end
>     end

As Mauricio pointed out this is factory pattern. And I see neither need
nor advantage of tampering with "new". The same is achieved with

module M
  def M.newState ...
    if ...
      return A.new
    elsif ...
      return B.new
    else
      return C.new
    end
  end
end


Why did you want to change "new" for this?

Another approach is to redefine methods to save the delegation instance

class Foo
  def st1
    def self.foo; 100; end
    def self.bar; 101; end
  end

  def st2
    def self.foo; 200; end
    def self.bar; 201; end
  end
end

f = Foo.new

f.st1
p f.foo
p f.bar

f.st2
p f.foo
p f.bar

Regards

    robert