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 ?
The initialize method is part of the object-creation process in Ruby & it allows you to set the initial values for an object. In other programming languages they call this a “constructor”.
Global variables start with dollar sign like. For Instance Variables: Instance variables can be initialized with @ symbol and the default value for it will be nil.
The initialize method is useful when we want to initialize some class variables at the time of object creation. The initialize method is part of the object-creation process in Ruby and it allows us to set the initial values for an object.
The main purpose of the initialization method is to set up the initial hierarchy of the RODM data cache. Some functions can be used only by the initialization method. The RODM load function can be used as the RODM initialization method. Parent topic: Object-Independent Methods.
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)
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With