2013-03-27 79 views

回答

6

根據它們被重寫的方式,它們不一定是二元的。

class Foo 
    def +; :plus end 
    def -; :minus end 
    def *; :asterisk end 
    def /; :slash end 
    def <; :lt end 
    def ==; :eq end 
    def >; :gt end 
end 

Foo.new.+ # => :plus 
Foo.new.- # => :minus 
Foo.new.* # => :asterisk 
Foo.new./ # => :slash 
Foo.new.< # => :lt 
Foo.new.== # => :eq 
Foo.new.> # => :gt 
+2

'必然二進制'是什麼意思? – HungryCoder 2013-03-27 06:47:47

+1

通常一個二元運算符需要兩個變量來處理。例如,操作'a + b'是二進制的,因爲它需要'a'和'b'來產生結果。然而,在ruby中,由於操作符也是方法,所以他們不一定需要兩個參數來生成sawa演示的結果。他的經營者沒有任何爭論,但仍然產生了結果。 – 2013-03-27 21:24:06

+0

繼續前面的例子,當你在Ruby中執行'a + b'時,你真的在​​做'a +(b)'。遵循sawa的例子,如果你要做'a = Foo.new',那麼你可以調用'a。+'並且得到':plus'! – 2013-03-27 21:26:24