From: Rick DeNatale Date: 2007-03-20T23:25:21+09:00 Subject: Re: does Ruby not support multiple "initialize" methods for a class??? On 3/20/07, Emilio Tagua wrote: > You could use: > > class Invitation > attr_reader :id, :date, :user, :text, :email > > def Invitation.withId(id) > return self.new(id) > end > > def Invitation.withAll(id, date, user, email, text) > return self.new(id, date, user, email, text) > end > > def initialize(id = 0, date = '', user = '', email = '', text = '') > super() > @id = id > @date = date > @email = email > @user = user > @text = text > end > end > > then: > > invitation = Invitation.withId(1) > > or with all params. Of course the only thing that the withId and withAll (*which in more normal Ruby style should be with_id and with _all) do is throw an error if you don't call them with the right number of parameters. With the above code you can also write: Invitation.new Invitation.new(42) Invitation.new(99, '10/22/2006') Invitation.new(35, '3/2/1907', 'Teddy Roosevelt') Invitation.new(67, '10/12/2010', 'Arthur C. Clarke', 'TheMan@theFuture.org') or Invitation.new(88, '6/6/1945', 'Dwight Eisenhower', 'leader@us.mil', 'I like Ike') Any of these work as defaults are provide dor all. Another approach would be to use a Hash to provide 'keyword' arguments. Invitation.new(:id => 20, :email => 'somene@somewhere.com') The initialize method would need to pick the hash argument apart. def initialize(options={}) # process options and set iv's etc. end You could combine this with additional parameters before the hash parameter. * Normal ruby style is to reserve 'camel case' for Globals (e.g. class and module names) and use underscores as separators in variable names. I keep tripping up on that when my old Smalltalk habits kick in. It's not crucial, but when in Ruby do as the Rubyists do. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/