LoginSignup
9
8

More than 5 years have passed since last update.

Rubyでnewした時に違うクラスを生成する

Posted at

Rubyって何でもできるんですね。

class A
  attr_reader :x
  def initialize(x)
    @x = x
  end
end

class B
  def self.new(x)
    obj = A.allocate
    obj.send(:initialize, x)
    obj
  end
end

b = B.new('abc')
puts b.class # => A
puts b.x # => abc

もちろん多用すると収拾がつかなくなるだけですが、
newの引数によって別のサブクラスを生成したい場合などは、
自然な呼び出し方ができますね。

継承した時などに思わぬ挙動をすることがあるようなので、
いろいろ試行錯誤中。
それも考慮した書き方もできそうです。

9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8