From: "Mauricio Fernández" Date: 2003-07-19T14:55:49+09:00 Subject: Re: Default constructor On Sat, Jul 19, 2003 at 11:03:01AM +0900, Pablo Lorenzzoni wrote: > Hello! > > class Klass > attr_accessor :att1, :att2 > def initialize(att1, att2) > @att1 = att1 > @att2 = att2 > end > .... > end > > Is it just me or the construction above is rather common? Is there such a > thing as a default cosntructor? Something that could turn that into > > class Klass > attr_accessor :att1, att2 > initializer(att1,att2) > end > > or even > > class Klass > attr_accessor :att1, :att2 > initializer > end This is similar to but not exactly what you want (see below) >> Klass = Struct.new(:att1, :att2) => Klass >> a = Klass.new "foo", :bar => # >> a.att1 => "foo" >> a.att2 => :bar >> a.att1 = 1 => 1 >> a.att1 => 1 however >> class Klass >> def foo >> puts "#{@att1} and #{@att2}" >> end >> end => nil >> a.foo (irb):9: warning: instance variable @att1 not initialized (irb):9: warning: instance variable @att2 not initialized and => nil so you need to use accessors even inside methods. -- _ _ | |__ __ _| |_ ___ _ __ ___ __ _ _ __ | '_ \ / _` | __/ __| '_ ` _ \ / _` | '_ \ | |_) | (_| | |_\__ \ | | | | | (_| | | | | |_.__/ \__,_|\__|___/_| |_| |_|\__,_|_| |_| Running Debian GNU/Linux Sid (unstable) batsman dot geo at yahoo dot com Steal my cash, car and TV - but leave the computer! -- Soenke Lange