Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby defining operator procedure

Tags:

ruby

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

a = MyObj.new()
b =  MyObj.new()

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

this is nicer than:

c = a.multiply(b)
...

thanks

like image 897
microo8 Avatar asked Apr 05 '11 17:04

microo8


2 Answers

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

like image 170
Phrogz Avatar answered Sep 27 '22 22:09

Phrogz


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"
like image 28
Michael Kohl Avatar answered Sep 27 '22 21:09

Michael Kohl