【戻る】 【進む】   目次        47. 動的プログラミング - 手法

手法

eval
class Foo
  def initialize(m)
    eval <<-ENDeval
      def meth(x)
        #{m}
      end
    ENDeval
  end
end
str = ["'A'*x", %"'B'*x"][0]
foo = Foo.new(str)
p foo.meth(5)
dynamic0.rb
send
class Foo
  def initialize(m)
    @meth = m
  end
  def methA(x); "A"*x; end
  def methB(x); "B"*x; end
  def meth(x); send(@meth, x); end
end
sym = [:methA, :methB][0]
foo = Foo.new(sym)
p foo.meth(5)
dynamic1.rb
Method
class Foo
  def initialize(sw)
    @meth = method sw
  end
  def methA(x); "A"*x; end
  def methB(x); "B"*x; end
  def meth(x); @meth.call(x); end
end
sym = [:methA, :methB][0]
foo = Foo.new(sym)
p foo.meth(5)
dynamic2.rb
Proc
def methA(x); "A"*x; end
def methB(x); "B"*x; end
class Foo
  def initialize(meth)
    @meth = meth
  end
  def meth(x); @meth.call(x); end
end
pro = [proc{|x| methA(x)},
       proc{|x| methB(x)}][0]
foo = Foo.new(pro)
p foo.meth(5)
dynamic3.rb
extend
module A
  def meth(x); "A"*x; end
end
module B
  def meth(x); "B"*x; end
end
class Foo
  def initialize(m)
    extend m
  end
end
mod = [A, B][0]
foo = Foo.new(mod)
p foo.meth(5)
dynamic4.rb
Delegation
class A
  def meth(x); "A"*x; end
end
class B
  def meth(x); "B"*x; end
end
class Foo
  def initialize(m)
    @meth = m
  end
  def meth(x)
    @meth.meth(x)
  end
end
dele = [A, B][0].new
foo = Foo.new(dele)
p foo.meth(5)
dynamic6.rb
FactoryMethod
class A
  def meth(x); "A"*x; end
end
class B
  def meth(x); "B"*x; end
end
class Foo
  def initialize
    @meth = factory.new
  end
  def meth(x)
    @meth.meth(x)
  end
end
class FooA < Foo
  def factory; A; end
end
class FooB < Foo
  def factory; B; end
end
klas = [FooA, FooB][0]
foo = klas.new
p foo.meth(5)
dynamic5.rb
ParametorizedClass
module ParamClass
  def [](*x)
    klass = type.new(self)
    klass.class_eval do
      for mod in x do include mod end
    end
    klass
  end
end

module A
  def meth(x); "A"*x; end
end
module B
  def meth(x); "B"*x; end
end
class Foo; extend ParamClass end
mod = [A, B][0]
foo = Foo[mod].new
p foo.meth(5)
dynamic7.rb

【戻る】 【進む】   目次        47. 動的プログラミング - 手法