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
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With