sarunw
sarunw

Reputation: 8176

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 ?

Upvotes: 6

Views: 11837

Answers (2)

Chuck
Chuck

Reputation: 237060

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

Upvotes: 9

Geo
Geo

Reputation: 96827

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).

Upvotes: 12

Related Questions