Once you've found an interesting object, you may be tempted to find
out just what it can do. Unlike static languages, where a variable's
type determines its class, and hence the methods it supports, Ruby
supports liberated objects. You really cannot tell exactly what an
object can do until you look under its hood.
[Or under its bonnet, for
objects created to the east of the Atlantic.]
For instance, we can get a list of all the methods to which an object will
respond.
r = 1..10 # Create a Range object
|
list = r.methods
|
list.length
|
� |
60
|
list[0..3]
|
� |
["size", "end", "length", "exclude_end?"]
|
Or, we can check to see if an object supports a particular method.
r.respond_to?("frozen?")
|
� |
true
|
r.respond_to?("hasKey")
|
� |
false
|
"me".respond_to?("==")
|
� |
true
|
We can determine our object's class and its unique object id, and test
its relationship to other classes.
num = 1
|
num.id
|
� |
3
|
num.class
|
� |
Fixnum
|
num.kind_of? Fixnum
|
� |
true
|
num.kind_of? Numeric
|
� |
true
|
num.instance_of? Fixnum
|
� |
true
|
num.instance_of? Numeric
|
� |
false
|