Reputation: 1824
Hoping to poll the collective consciousness here since I can't structure this in a way to find an answer via search. In Ruby 1.9+, calling .methods on an instance will yield different results than on the class of that instance. For example, "foo".methods will include 'length' and 'size' whereas String.methods will not. What is the reason for this? I am a veteran programmer but new to Ruby. From my understanding, methods is supposed to include all ancestor methods, so is it through a mixin or some other pattern that length and size are added into the instance's list but not the class's?
Upvotes: 1
Views: 240
Reputation: 160181
Length and size are String instance methods, why would they be included in a list of String's (a class) methods? Classes are objects and have their own methods.
In other words, you get the list of methods supported by the object you're calling it on. String is a class, so you get its specific class methods, plus class methods it inherits.
A string instance is an instance, so you get string's instance methods, and instance methods it inherits.
Upvotes: 2
Reputation: 28753
You're confusing .methods()
with .instance_methods()
.
The first will give you the methods which can be invoked on the String
object - that is the String
class as an object itself. The second will give you the methods of objects created using the String
class, or instances of String
.
Upvotes: 2