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?
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.
Add a refinement to check if a rectangle is a square, the Ruby way:
class CRectangle
def square? @width == @height
end
end
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.
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.