From: Jens Wille Date: 2008-05-08T22:18:36+09:00 Subject: Re: Why can't I redefine "<<" method to allow two parameters? Jason Roelofs [2008-05-08 14:50]: > On Thu, May 8, 2008 at 8:42 AM, I�aki Baz Castillo wrote: >> Hi, very exrtange: >> >> >> class MyArray < Array >> alias original_add << >> def <<(n,k) >> original_add "#{n}: #{k}" >> end >> end >> >> my_array = MyArray.new >> => [] >> >> my_array << ("Header", "Value") >> >> SyntaxError: compile error >> (irb):25: syntax error, unexpected ',', expecting ')' >> my_array << ("Header", "Value") >> ^ >> >> >> Any reason for this? It seems that << is a littled "hardcoded", isn't? >> >> -- >> I�aki Baz Castillo >> >> > > The << operator is a special case handled by the parser, but you can > bypass that handling by calling the method directly: the point is that you can't call an operator with multiple arguments. maybe something like this will suit you (note that you don't need to alias if you inherit from Array): class MyArray < Array def <<(*a) a = [*(a=*a)] # a.to_a.flatten_once ;-) raise ArgumentError, "wrong number of arguments (#{a.size} for 2)" if a.size != 2 super a.join(': ') end end my_array = MyArray.new my_array << ['Header1', 'Value1'] # => ["Header1: Value1"] my_array.<<('Header2', 'Value2') # => ["Header1: Value1", "Header2: Value2"] cheers jens -- Jens Wille, Dipl.-Bibl. (FH) prometheus - Das verteilte digitale Bildarchiv f�r Forschung & Lehre Kunsthistorisches Institut der Universit�t zu K�ln Albertus-Magnus-Platz, D-50923 K�ln Tel.: +49 (0)221 470-6668, E-Mail: jens.wille@uni-koeln.de http://www.prometheus-bildarchiv.de/