Overloaded constructor

Hello
I want I ask something I am using ruby192 I want to know if it can
support overloaded constructor
for example
if i want to write this c++ code in ruby
class CRectangle {
int width, height;
public:
CRectangle (int,int);
CRectangle(int);
int area () {return (width*height);}
};

CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
CRectangle::CRectangle (int a) {
width = a;
height = a;
}
What should I do?

On Tue, Sep 20, 2011 at 03:11:05AM +0900, Aya A. wrote:

Hello
I want I ask something I am using ruby192 I want to know if it can
support overloaded constructor

AFAIK it can’t.

On Mon, Sep 19, 2011 at 8:11 PM, Aya A. [email protected]
wrote:

CRectangle::CRectangle (int a, int b) {
width = a;
height = b;
}
CRectangle::CRectangle (int a) {
width = a;
height = a;
}
What should I do?

class CRectangle
def initialize( width, height = width )
@width = width
@height = height
end
def area
@width * @height
end
end

square = CRectangle.new(2)
rectangle = CRectangle.new(2, 4)

puts “Square area: #{square.area}”
puts “Rectangle area: #{rectangle.area}”

Basically, just assign a default value for height, and you don’t even
need overloading. That way, your code does the right thing, without
confusing matters unnecessarily. :wink:

Add a refinement to check if a rectangle is a square, the Ruby way:

class CRectangle
def square?
@width == @height
end
end


Phillip G.

gplus.to/phgaw | twitter.com/phgaw

A method of solution is perfect if we can forsee from the start,
and even prove, that following that method we shall attain our aim.
– Leibniz

Oh ok Thank you

Thank you very much Phillip:)

On 9/19/2011 13:38, Phillip G. wrote:

But keep in mind that default values for an assignment is a feature
introduced in Ruby 1.9. If you have to deal with 1.8, you’ll need an
option hash. Google should have numerous examples of how to achieve
that.

Phillip, your code runs just fine on Ruby 1.8.7 as-is. Default values
for method parameters are supported there, if that’s what you’re talking
about.

-Jeremy

On Mon, Sep 19, 2011 at 8:29 PM, Aya A. [email protected]
wrote:

Thank you very much Phillip:)

No problem!

But keep in mind that default values for an assignment is a feature
introduced in Ruby 1.9. If you have to deal with 1.8, you’ll need an
option hash. Google should have numerous examples of how to achieve
that.


Phillip G.

gplus.to/phgaw | twitter.com/phgaw

A method of solution is perfect if we can forsee from the start,
and even prove, that following that method we shall attain our aim.
– Leibniz

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs