#Ruby# Introspect (2)

3. Looking at Classes

 

superclass => get the parent of any particular class

 

ancestors => get both superclasses and mixin modules

 

在Ruby1.9中,任何未指定的class都继承自Object,而Object继承自BasicObject,BasicObject无superclass。

 

4. Looking inside Classes

 

 

class Demo
end

Demo.private_instance_methods(false)
Demo.protected_instance_methods(false)
Demo.public_instance_methods(false)
Demo.singleton_methods(false)
Demo.class_variables
Demo.constants(false)

 

 

5. Calling Mehods Dynamically

 

 

obj.method(sym)    -> method

 

Looks up the named method as a receiver in obj, returning a Method

object (or raising NameError). The Method object acts as a closure in

obj's object instance, so instance variables and the value of self

remain available.

 

 

 

len="hello".method(:length)
len.call # => 5

也可以这样使用:

def double(a)
     2*a
end
method_object = method(:double)
[ 1, 3, 5, 7 ].map(&method_object)

或者:

str = %q{puts "hello".length}

eval str # => 5

 

 

你可能感兴趣的:(Ruby,Introspect)