From: "David A. Black" Date: 2004-05-03T03:52:27+09:00 Subject: Re: The code I forgot to include Hi -- On Mon, 3 May 2004, Richard Lionheart wrote: > # My idea of how to convert an array of strings to a string with a specified > delimiter That sounds an awful lot like Array#join.... > class MyArrayType1 < Array > def [](a) > puts "Entering MyArrayType1#[](a) -- calling parent" > super a > end > def to_s > s = "" > self.each { |x| > s += "; " if s.length>0 > s += x.to_s > } > s > end Yikes -- let Ruby do the work for you: def to_s join("; ") end :-) > end > > myA1 = MyArrayType1['x1', 'y1'] # uses the Array#[](a) method with an Array > argument and sets Actually it's a different [] method that's getting called. It works like this (using Array instead of MyArrayType1 for convenience): Array[1,2,3] is just Ruby shorthand for this: Array.[](1,2,3) i.e., call the method [] on the object Array (which is a Class object), with the arguments (1,2,3). That's different from, say, this: a = [1,2,3] puts a[0] # call [] on a, which is an Array object (i.e., an # instance of Array) In other words, the Class object Array responds to [], and so does every array... but the two [] methods are not the same as each other. Indeed, there's no connection between these two methods, except that they happen to have been given the same name. What the class object Array does or does not respond to is an entirely separate matter from the matter of what a given instance of the class Array responds to. Like much else in Ruby, it comes down to the "a class is, itself, an object" principle. Here's how it's set up, at least conceptually: class Array def Array.[](*args) # gets called when you do Array[1,2,3] end def [](*args) # gets called when you do # a = [1,2,3]; puts a[0] end end The first [] is a singleton (i.e., callable through one object only) method belonging to the Class object Array; singleton methods belonging to class objects are also referred to as "class methods". The second [] is an instance method of Array -- meaning, a method to which every instance of Array will respond. David -- David A. Black dblack@wobblini.net