From: ahoward Date: 2003-06-12T05:15:26+09:00 Subject: Re: Multiple Initialize methods? On Wed, 11 Jun 2003, Nick wrote: > Hi, > > I need to create a class either with a param in the construction or nothing: > > something = Object.new > > or > > something = Object.new(val1, val2) > > I have created an emtpy initialize() method and one with the two params. If > I try to create the object with nothing (first version) then I get > "ArgumentError: wrong number of arguments(0 for 2)". > > class Something > def initialize() > end > def initialize(xdim, ydim) > @xdim = xdim > @ydim = ydim > end > > I put the empty initialze in when things didnt work, thinking i needed at > least a marker. > > Thanks for any help, ruby does not support method overloading - you may only a single method signature for a give name. you can do something like: ~ > cat foo class Klass def initialize(*args) args.size == 0 ? init0() : init1(*args[0..1]) end private def init0 @x = 4 @y = 2 end def init1 x, y @x = x @y = y end def inspect; @x.to_s << @y.to_s; end end k = Klass.new p k k = Klass.new 4, 2 p k class Klass def initialize args = {} @x = args[:x] || 4 @y = args[:y] || 2 end end k = Klass.new p k k = Klass.new :x => 4, :y => 2 p k ~ > ruby foo 42 42 42 42 -a -- ==================================== | Ara Howard | NOAA Forecast Systems Laboratory | Information and Technology Services | Data Systems Group | R/FST 325 Broadway | Boulder, CO 80305-3328 | Email: ara.t.howard@noaa.gov | Phone: 303-497-7238 | Fax: 303-497-7259 | ~ > ruby -e 'p(%.\x2d\x29..intern)' ====================================