Ruby 3.0.0 リファレンスマニュアル > ライブラリ一覧 > 組み込みライブラリ > Objectクラス > respond_to?
respond_to?(name, include_all = false) -> bool
[permalink][rdoc]オブジェクトがメソッド name を持つとき真を返します。
オブジェクトが メソッド name を持つというのは、オブジェクトが メソッド name に応答できることをいいます。
Windows での Process.fork や GNU/Linux での File.lchmod のような NotImplementedError が発生する場合は false を返します。
※ NotImplementedError が発生する場合に false を返すのは Rubyの組み込みライブラリや標準ライブラリなど、C言語で実装されているメソッドのみです。 Rubyで実装されたメソッドで NotImplementedError が発生する場合は true を返します。
メソッドが定義されていない場合は、Object#respond_to_missing? を呼び出してその結果を返します。
class F
def hello
"Bonjour"
end
end
class D
private
def hello
"Guten Tag"
end
end
list = [F.new,D.new]
list.each{|it| puts it.hello if it.respond_to?(:hello)}
#=> Bonjour
list.each{|it| it.instance_eval("puts hello if it.respond_to?(:hello, true)")}
#=> Bonjour
# Guten Tag
module Template
def main
start
template_method
finish
end
def start
puts "start"
end
def template_method
raise NotImplementedError.new
end
def finish
puts "finish"
end
end
class ImplTemplateMethod
include Template
def template_method
"implement template_method"
end
end
class NotImplTemplateMethod
include Template
# not implement template_method
end
puts ImplTemplateMethod.new.respond_to?(:template_method) # => true
# NotImplementedError が発生しているが、Rubyによる実装部のため true を返す
puts NotImplTemplateMethod.new.respond_to?(:template_method) # => true
# GNU/Linux で実行。C言語による実装部のため false を返す
puts File.respond_to?(:lchmod) # => false
[SEE_ALSO] Module#method_defined?