开发者

Ruby defining operator procedure

how can a write a class in ruby that has a procedures that i can call like this:

a = MyObj.new(开发者_StackOverflow)
b =  MyObj.new()

c = a * b
d = a / b
e = a - b

this is nicer than:

c = a.multiply(b)
...

thanks


class Foo
  attr_accessor :value
  def initialize( v )
    self.value = v
  end
  def *(other)
    self.class.new(value*other.value)
  end
end

a = Foo.new(6)
#=> #<Foo:0x29c9920 @value=6>

b = Foo.new(7)
#=> #<Foo:0x29c9900 @value=7>

c = a*b
#=> #<Foo:0x29c98e0 @value=42>

You can find the list of operators that may be defined as methods here:
http://phrogz.net/ProgrammingRuby/language.html#operatorexpressions


You already got an answer on how to define the binary operators, so just as little addendum here's how you can define the unary - (like for negative numbers).

>  class String
..   def -@
..     self.swapcase
..   end
.. end #=> nil
>> -"foo" #=> "FOO"
>> -"FOO" #=> "foo"


Just create methods whose name is the operator you want to overload, for example:

class MyObj
   def / rhs
     # do something and return the result
   end
   def * rhs
     # do something and return the result
   end
end


In Ruby, the * operator (and other such operators) are really just calling a method with the same name as the operator. So to override *, you could do something like this:

class MyObj
  def *(obj)
    # Do some multiplication stuff
    true    # Return whatever you want
  end
end

You can use a similar technique for other operators, like / or +. (Note that you can't create your own operators in Ruby, though.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜