From: Stefano Crocco Date: 2012-09-01T16:03:48+09:00 Subject: Re: Constructor or a Method On Saturday 01 September 2012 Rubyist Rohit wrote > Take for instance this code: > > ======== [CODE] ======= > def Customer > attr_accessor :name > > def name > @name > end > > def name(=str) > @name = str > end > end > ======================= > > I want to know: > > (1) Is 'name' a constructor or a method? It's a normal method. What you'd call a "constructor" in other languages, in ruby is the initialize method. > (2) In case I ignore '=' in second method, will it work? Why '=' is > necessary? If you omit the = in the second method, you'll define a method called "name" which takes one argument and makes the instance variable @name point to the str object. This will override the previously defined name method. Also, you won't be able to do something like: Customer.new.name = 'x' but only Customer.new.name 'x' which, depending on circumstances, may be unexpected. Note that both the method definitions are useless here, as using attr_accessor already creates two methods doing exactly what your hand-written methods do. I hope this helps Stefano