[Note: parts of this message were removed to make it a legal post.]
Robert, I get the point. However it's important to notice that there's no such
thing as operator overloading in Ruby. Things like :+, :-, :*, etc, are just
plain methods. You can achieve what you want by opening the Fixnum class and
redefining the method :+. Important to say is that all instances of this will be
affected as soon as you make the change.
Eg:
class Fixnum
def -(x)
self + x
end
end
puts 1 - 1 # => 2
Another tip: In Ruby, every expression returns a value, so there's no need to
explicit the 'return'.
Regards,
Adriano
________________________________
From: Robert Klemme <>
To: ruby-talk ML <ruby->
Sent: Thu, September 30, 2010 3:10:35 AM
Subject: Re: Operator Overload
On 09/28/2010 03:49 AM, Trevor Hinesley wrote:
> Hey guys,
>
> I'm slowly getting the hang of Ruby, I'm a Java guy by trade. I really
> like Ruby and am picking up on it pretty quickly, but for some reason my
> overload of the "+" operator is not working. Here is the code:
>
> class Overloading
> def -(a)
> return -a
> end
> b = 2-4
> puts "#{b}"
> end
>
> Basically, I'm trying to turn the minus operator into a plus operator
> for a project to show how operator overloading in Ruby works, but this
> isn't working from some reason, and I'm not sure why.
>
> Help?
This might be interesting for you:
http://blog.rubybestpractices.com/po...ric_Class.html
Kind regards
robert