Julien Gaugaz
12/21/2006 4:08:00 PM
Hi!
It's several hours now that i'm trying to find out what's special with
*** for a method name, without success :(
I'm trying to add an element wise multiplication method to the Matrix
class. For this I created a collect2 method for Matrix similar to the
one in Vector as follows:
class Matrix
def collect2(other)
result = self.clone
(0...self.row_size).each {|rowi|
(0...self.column_size).each {|columni|
result[rowi,columni] = yield (self[rowi,columni],
other[rowi,columni])
}
}
result
end
def []=(i,j,v)
@rows[i][j] = v
end
end
And i would like now to add a method *** to Matrix such that we could
call matrix1 *** matrix2. Like:
m = Matrix[[1,2,3],[-1,-2,-3], [4,5,6]]
n = Matrix[[1,2,3],[7,8,9], [-1,-2,-3]]
m *** n
=> Matrix[[1, 4, 9], [-7, -16, -27], [-4, -10, -18]]
Now if I define this method as follows:
def ***(other)
collect2(other) do |e1,e2|
if(e1 and e2)
e1*e2
end
end
end
I get the following error:
SyntaxError: compile error
(irb):550: parse error, unexpected tLPAREN, expecting '\n' or ';'
def ***(other)
^
(irb):557: parse error, unexpected kEND, expecting $
from (irb):557
from :0
The same with def *** other works (I can define it without error).
But now a call to m *** n gives me:
SyntaxError: compile error
(irb):33: parse error, unexpected tSTAR
m *** n
^
from (irb):33
from :0
And m.*** n (notice the period after m) gives:
TypeError: Array can't be coerced into Fixnum
from (irb):8:in `*'
from (irb):8:in `**'
from (irb):24:in `collect2'
from (irb):23:in `each'
from (irb):23:in `collect2'
from (irb):22:in `each'
from (irb):22:in `collect2'
from (irb):6:in `**'
from (irb):35
from :0
Whereas if I name the method with two stars only, i.e. def **(other), it
can be defined, and then m ** n gives the expected result.
I therefore have the following questions:
- Why is it possible to define def *** other but not def ***(other) ?
- What is the difference between m.*** n and m *** n (with and without
period after m) ?
- Why do I get an error with m.*** n (with period) but not with m ** n ?
I would greatly appreciate any answer of pointers to some information
sources (I tried but it is not easy to search for *** in a web search
engine ;-) )
Thanks a lot in advance for your help and advices!
Julien