jay s. wrote in post #1001040:
Say I want to extend the built in Array class with some useless function
Correct me if I’m wrong, but I now have a class method for Array.
You’re wrong, so I’ll correct you “def” creates instance methods.
You now have a new instance method on class Array; that is, a method
which is available to all objects which are instances of Array.
call Array.methods just to make sure that it is there, yet it doesn’t
show up, however if I do this:
a = 
and then call a.methods, I can see the crazy() method that we wrote
Yes. To call that method, you’d do “a.crazy”
It looks to me as if I am creating an instance method, but I
would think I would do that like this:
That would create a singleton method: a method which belongs only to
a = 
a.crazy # works
b = 
b.crazy # NoMethodError
What you did before was this:
That defines an instance method on class Array - that is, a method which
is available to all array objects, even arrays which existed before you
defined the method. This is the “normal” sort of method you define when
Just to close the loop, here’s how you do class methods:
Now, that syntax may look familiar. In Ruby, classes are objects. You
are defining a singleton method on the object “Array” (which also
happens to be an object of class “Class”)
So, “class methods” are nothing more than singleton methods, on an
object of class Class.
Does this issue have anything to do with the face that the Array class
No, and in any case the class Array is definitely not immutable.
$ irb --simple-prompt
a = [1,2]
=> [1, 2]
a << 3
=> [1, 2, 3]
=> [1, 2, 3]
I’m a bit confused
That does appear to be the case You might want to work through some
documentation. This one is good:
And continue experimenting within irb of course.