パンくず
Ruby Cookbook
抽象メソッドの作成
概要
抽象メソッドの作成
内容
Rubyは言語として抽象メソッドをサポートしていないため、
Javaのような抽象メソッドを利用したい場合は自分で仕組みを用意する必要があります。
抽象メソッドとしてオーバーライドを強制したいメソッドの初期実装を
NotImplementedErrorにすることで対応します。
またクラスを抽象クラスにしたい場合はコンストラクタでNotImplementedErrorを
投げるようにすれば実質抽象クラスになります。
サンプルコード
# encoding: Windows-31J require "pp" class Hoge attr_accessor :name,:age def initialize(name,age) @name,@age = name,age end def print_hoge() print_each end def print_each() raise NotImplementedError.new("#{self.class.name}.#{current_method_name} is an abstract method.") end end class ExtendedHoge < Hoge def print_each() puts "#{@name},#{@age}" end end class Object def current_method_name caller.first.scan(/`(.*)'/).to_s.gsub(/\[|\]|\"/,'') end end extended_hoge = ExtendedHoge.new("extendedHoge",11) extended_hoge.print_hoge hoge = Hoge.new("hoge",10) hoge.print_hoge
出力
extendedHoge,11 C:/kt/mySite/ruby cookbook/8_class/14.rb:16:in `print_each': Hoge.print_each is an abstract method. (NotImplementedError) from C:/kt/mySite/ruby cookbook/8_class/14.rb:12:in `print_hoge' from C:/kt/mySite/ruby cookbook/8_class/14.rb:36:in `<main>'