6

I used to have this

public constructor_name() {
   this(param)
}

public constructor_name(int param) {
  this.param = param
}

in Java and what about ruby do we have this kind of self reference constructor ?

Greg Campbell
  • 15,182
  • 3
  • 44
  • 45
sarunw
  • 8,036
  • 11
  • 48
  • 84

2 Answers2

12

Since Ruby is a dynamic language, you can't have multiple constructors ( or do constructor chaining for that matter ). For example, in the following code:

class A
   def initialize(one)
     puts "constructor called with one argument"
   end
   def initialize(one,two)
     puts "constructor called with two arguments"
   end
end

You would expect to have 2 constructors with different parameters. However, the last one evaluated will be the class's constructor. In this case initialize(one,two).

Geo
  • 93,257
  • 117
  • 344
  • 520
  • 6
    Why would you argue that the fact that you cannot have multiple constructors is related to Ruby being a dynamic language? As far as I can see this is a design decision that is unrelated to whether the language is dynamic or not. – Cumbayah Dec 13 '12 at 12:52
  • 1
    @Cumbayah Sorry for reviving this, but for future readers: the author may have meant that Ruby is executed (in some aspects) as if it was in a interactive session, so defining a function twice replaces the older one. – This company is turning evil. Jul 16 '14 at 02:54
9

Those aren't valid Java, but I think what you're getting at is that you want an optional argument. In this case, you could either just give the argument a default value

 def initialize(param=9999)
 ...
 end

or you could use a splat argument:

def initialize(*params)
  param = params.pop || 9999
end
rogerdpack
  • 62,887
  • 36
  • 269
  • 388
Chuck
  • 234,037
  • 30
  • 302
  • 389