From: Robert Klemme Date: 2010-01-28T05:50:06+09:00 Subject: Re: Class with Multi Constrcutor ( initialize ) On 27.01.2010 16:58, Pierre Lecocq wrote: > Hello Mido, > > There are several solutions to this problem. > > The first one is this equivalent of vaargs in C language > > def initialize(*args) > args.each do |a| > puts a.class.inspect > end > end > > The second one is to pass a hash or an array in parameter. > > And the third is to put default values to your args: > > def initialize(var1='', var2=0, var3=nil) > end > > Hope i helped ! A solution like this was proposed for overloading once but it does not seem to be widely used: irb(main):001:0> def overload(*a) irb(main):002:1> case a.map {|x|x.class} irb(main):003:2> when [String] irb(main):004:2> puts "a single string" irb(main):005:2> when [Fixnum, String] irb(main):006:2> puts a[1] * a[0] irb(main):007:2> else irb(main):008:2* raise ArgumentError, "can't %p" % a irb(main):009:2> end irb(main):010:1> end => nil irb(main):011:0> overload "foo" a single string => nil irb(main):012:0> overload 2, "foo" foofoo => nil irb(main):013:0> overload 2 ArgumentError: can't 2 from (irb):8:in `overload' from (irb):13 from /usr/local/bin/irb19:12:in `
' irb(main):014:0> You can even shorten that to case a.map(&:class) ... Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/