From: Brian Candler Date: 2011-05-26T06:20:57+09:00 Subject: Re: Method that mutates object jay s. wrote in post #1001040: > Say I want to extend the built in Array class with some useless function > called crazy() > > class Array > def crazy > ...do something... > end > end > > > 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. > I > 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 > available. 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: > > def a.crazy > ...do something... > end That would create a singleton method: a method which belongs only to that object. a = [] def a.crazy puts "hello" end a.crazy # works b = [] b.crazy # NoMethodError What you did before was this: class Array def crazy ... end end 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 programming. Just to close the loop, here's how you do class methods: def Array.crazy puts "wibble" end Array.crazy 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 > is immutable? 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] >> a => [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: http://www.ruby-doc.org/docs/ProgrammingRuby/ And continue experimenting within irb of course. Regards, Brian. -- Posted via http://www.ruby-forum.com/.