Ruby/Reflection/instance of

Материал из Wiki.crossplatform.ru

Перейти к: навигация, поиск

Содержание

if an object is an instance of a given class with the instance_of? method from Object

myString = "asdf"
puts myString.instance_of? String # => true
puts myString.instance_of? Fixnum # => false



Is it a number

x = 1                    # This is the value we"re working with
x.instance_of? Fixnum    # true: is an instance of Fixnum
x.instance_of? Numeric   # false: instance_of? doesn"t check inheritance



Is it a string class instance

o = "String"
o.class == String       # true if is o a String
o.instance_of? String   # true if o is a String



Unlike instance_of?, is_of? or kind_of? also work if the argument is a superclass or module.

myString = "asdf"
puts myString.is_a? Object # => true
puts myString.kind_of? Kernel # => true
puts myString.instance_of? Object # => false



Use instance_of? for robustness.

# don"t do the block (do |t|...end) unless the variable myString is a string.
myString = "asdf"
if myString.instance_of?( String )
  myString.split.each do |t|
     puts t
  end
end



Use === to check the class type

x = 1                    # This is the value we"re working with
 
Numeric === x            # true: x is_a Numeric