Transferred from: http://blog.sina.com.cn/s/blog_4901d7bd0100b6lf.htmlrubyoperator reload
Reprinted tokenRuby's Operator Overloading is very interesting. Ruby allows "+" and other operators to be used as function names. Therefore, it is similar to calling a function normally. The only difference is that you do not have to use ". "To define, use + directly. However, there must be a premise that only one parameter is defined after +. If there are two parameters, you must use ". ", and Ruby is not like C ++. It is required to distinguish between binary and single-object operators and follow the same principle: Unified operator functions, ". ", 2 or more, except for explicit use ". ", the real parameters of the function must also be surrounded. Example: Class clsaattr_accessor: mdef funclsa (x = 0) puts "CLSA" endendendclass clsb <clsadef funclsa Puts "clsb" enddef + (X, y)If X. Class! = Clsareturn "Wrong type"Elseui = x. m + mendendendc = clsb. new () C. M = 3cc = CLSA. new () CC. M = 4 puts C. + (CC, c) C. funclsa> Ruby test. rb7clsb> exit code: 0 =================================================== ========================================================== ===== class clsaattr_accessor: mdef funclsa (x = 0) puts "CLSA" endendclass clsb <clsadef funclsa Puts "clsb" enddef + XIf X. Class! = Clsareturn "Wrong type"Elseui = x. m + mendendendc = clsb. new () C. M = 3cc = CLSA. new () CC. M = 4 puts C + CCC. funclsa> Ruby test. rb7clsb> exit code: 0