From: Phillip Gawlowski Date: 2011-09-20T03:25:34+09:00 Subject: Re: Overloaded constructor On Mon, Sep 19, 2011 at 8:11 PM, Aya Abdelsalam 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? 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 -- 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