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?
···
--
Posted via http://www.ruby-forum.com/.
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. 
Add a refinement to check if a rectangle is a square, the Ruby way:
class CRectangle
def square?
@width == @height
end
end
···
On Mon, Sep 19, 2011 at 8:11 PM, Aya Abdelsalam <ayoya_91@hotmail.com> wrote:
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?
--
Phillip Gawlowski
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
Thank you very much Phillip:)
···
--
Posted via http://www.ruby-forum.com/.
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.
···
On Mon, Sep 19, 2011 at 8:29 PM, Aya Abdelsalam <ayoya_91@hotmail.com> wrote:
Thank you very much Phillip:)
--
Phillip Gawlowski
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
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 9/19/2011 13:38, Phillip Gawlowski 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.