0

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?

1
  • Ruby has a Complex class out of the box: puts '0.3-0.5i'.to_c.class #=>Complex Commented May 27, 2012 at 20:45

2 Answers 2

3

The best way (in my opinion) would be to provide a read only access to the variables real and imag using attr_reader. Like:

class ComplexNumber
  attr_reader :imag, :real
  ...
  def +(other)
    return ComplexNumber.new(@real + other.real, @imag + other.imag)
  end
end

Note that attr_reader defines the methods on your behalf .real() and .imag() [attr_accessor additionally defines .real=() and .image=()]

Sign up to request clarification or add additional context in comments.

4 Comments

So the four methods are private, I assume?
@WChargin Why do you assume that?
Because there are set methods, which seem intrusive. Is it just the set methods that are private and the get methods are public?
@WChargin No; they're all public. You can look up the docs for those methods (attr_accessor, attr_reader, etc.) too.
1

Instance variables are accessed without the @ when referring to another instance:

other.real

(Assuming you're either using attr_accessor to define them, or are providing your own accessors. Even within the same instance you may prefer to use the accessors in case there's logic beyond simply returning the instance variable.)

2 Comments

When I used other.real, it assumed real was a method and threw an error. What's attr_accessor?
@WChargin apidock.com/ruby/Module/attr_accessor I don't know why you'd create a complex class without providing accessors for the different parts; almost anything with complex numbers would need them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.