Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 942
sarunw Avatar asked Nov 07 '09 15:11

sarunw


People also ask

What is initialize in Ruby?

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

How do you initialize a variable in Ruby?

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.

Why do we initialize variables in Ruby?

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.

What is initialization method?

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.


2 Answers

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

like image 119
Geo Avatar answered Oct 10 '22 20:10

Geo


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
like image 33
Chuck Avatar answered Oct 10 '22 19:10

Chuck