I've been messing around with Ruby (Ruby 1.9.3, IRB 0.9.6(09/06/30)) and I'm trying to develop a complex number class. I have the initialize and to_s methods working fine. I'm now trying to overload the four arithmetic operators.
What I had is the following:
def +(other)
return ComplexNumber.new(@real + other.@real, @imag + other.@imag)
end
but for some reason it didn't like other.@real; it says
syntax error: unexpected tIVAR
and points to the comma after other.@real.
So then I changed it to:
def get_values
return [@real, @imag]
end
def +(other)
other_values = other.get_values
return ComplexNumber.new(@real + other_values[0], @imag + other_values[1])
end
Although this works, I have a feeling that it's not the correct way to do it. I don't really want to expose the get_values method; isn't there some way I can access a variable of another instance of the same class?
puts '0.3-0.5i'.to_c.class #=>Complex