Initialize in Ruby

I used this

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

in Java, and what about Ruby, do we have such a self reference constructor?

+6
initialization ruby
source share
2 answers

Since Ruby is a dynamic language, you cannot have multiple constructors (or, if necessary, a chain of constructors). 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 expect to have 2 constructors with different parameters. However, the last one that has been evaluated will be the constructor of the class. In this case, initialize(one,two) .

+12
source share

This is not valid Java, but I think that you get what you need an additional argument. In this case, you can either just give the argument a default value

  def initialize(param=9999) ... end 

or you can use splat argument:

 def initialize(*params) param = params.pop || 9999 end 
+9
source share

All Articles