Ruby クラスメソッドでコンストラクタを実行するサンプル
環境
Windows11 Pro 64bit
ruby 3.1.2p20
構文
class クラス名
def initialize(変数名)
@num = 変数名
end
# 擬似的なコンストラクタ
def クラス名.setval
クラス名.new(値)
end
class クラス名
def initialize(変数名)
@num = 変数名
end
# 擬似的なコンストラクタ
def クラス名.setval
クラス名.new(値)
end
class クラス名 def initialize(変数名) @num = 変数名 end # 擬似的なコンストラクタ def クラス名.setval クラス名.new(値) end
使用例
class Sample
def initialize(n)
@cft = n
end
# 擬似的なコンストラクタ
def Sample.setval
Sample.new(6)
end
def show
p @cft
end
end
cftA = Sample.new(8)
cftA.show
cftB = Sample.setval # クラスメソッドから実行
cftB.show
class Sample
def initialize(n)
@cft = n
end
# 擬似的なコンストラクタ
def Sample.setval
Sample.new(6)
end
def show
p @cft
end
end
cftA = Sample.new(8)
cftA.show
cftB = Sample.setval # クラスメソッドから実行
cftB.show
class Sample def initialize(n) @cft = n end # 擬似的なコンストラクタ def Sample.setval Sample.new(6) end def show p @cft end end cftA = Sample.new(8) cftA.show cftB = Sample.setval # クラスメソッドから実行 cftB.show
実行結果
8
6