views:

557

answers:

2
+1  Q: 

Initialize in Ruby

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 ?

+5  A: 

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) or you could use a splat argument:

def initialize(*params)
  param = params.pop || 9999
end
Chuck
+1  A: 

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