From: Albert Schlef Date: 2008-05-08T03:46:15+09:00 Subject: Re: get method in Array subclass: where's it defined? Daniel Finnie was faster than me ;-) but I'll my answer nevertheless; it duplicates some of his. RichardOnRails wrote: > > [...] is my ignorance about the def [] * args. There are two _unrelated_ features in that syntax: the '*' and the '[]'. Let's start with a simple method that accept one argument: def simple(one) puts one end Now, let's extend it to accept two arguments: def simple(one, two) puts one, two end But what if we wanted this method to accept _any_ number of arguments? We would use the '*' syntax, that tells Ruby to lumb all arguments into an array: def simple(*all) all.each { |i| puts i } end We can invoke this method thus: simple 4 simple simple 9, 4, "blah" simple -3, 5.6 ====== That's all for the '*'. Now, for the '[]': let's look at this expression: m[4] The 'm' object would return the 4th element. It has to have some method that responds to this request. Ruby would invoke this method whenever the '[]' syntax is used. But what would be the name of this method? The answer is simple: []. So we define a '[]' method that would be invoked whenever we do "some_object [ some_thing ]". Here it is: class Matrix def [] (one, two, three) puts "hello #{one}" puts "hello #{two}" puts "hello #{three}" end end Now, it we did: m = Matrix.new m[100, 77, "box"] We'd see: hello 100 hello 77 hello box We could use the '*' syntax to allow for _any_ number of arguments, not just three: class Matrix def [] (*args) args.each { |a| puts "hello #{a}" } end end m = Matrix.new m["how", "nice", "to", "have", 13, "chocolates"] Note that "def [] *args" is a synonym for "def [] (*args)". Parentheses aren't mandatory in Ruby. -- Posted via http://www.ruby-forum.com/.