如何在Ruby中覆盖常规二进制运算符,如+, - ,*,/?

One*_*ero 3 ruby

如何重写常见的运营商,如+,-,*,/,<,==,>,等一类?

saw*_*awa 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
Run Code Online (Sandbox Code Playgroud)

  • "必然是二元的"是什么意思? (2认同)