Ruby/Reflection/respond to
Материал из Wiki.crossplatform.ru
Check respond_to? for new added instance method
class MyClass def MyClass.my_singleton_method end def my_instance_method end end p MyClass.respond_to? :my_instance_method # => false
Check respond_to? for new added singleton method
class MyClass def MyClass.my_singleton_method end def my_instance_method end end p MyClass.respond_to? :my_singleton_method # => true
Testing Whether an Object Is String-like
"A string".respond_to? :to_str # => true Exception.new.respond_to? :to_str # => true 4.respond_to? :to_str # => false
The method respond_to? tests to see whether an instance of Address has access to :given_name, inherited from the Name class.
#!/usr/bin/env ruby class Name attr_accessor :given_name, :family_name end class Address < Name attr_accessor :street, :city, :state, :country end a = Address.new puts a.respond_to?(:given_name) # => true
The respond_to? method from Object checks to see if a given object responds to a given method.
class A attr_accessor :x end a = A.new a.respond_to? :x # => true a.respond_to? :x= # => true a.respond_to? :y # => false