A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor may also contain the group of instructions or a method which will execute at the time of object creation.
Important points to remember about Constructors:
- Constructors are used to initialize the instance variables.
- In Ruby, the constructor has a different name, unlike other programming languages.
- A constructor is defined using the initialize and def keyword.
- It is treated as a special method in Ruby.
- Constructor can be overloaded in Ruby.
- Constructors can’t be inherited.
- It returns the instance of that class.
Note: Whenever an object of the class is created using new method, internally it calls the initialize method on the new object. Also, all the arguments passed to new will automatically pass to method initialize.
class Class_Name def initialize(parameter_list) end end
Welcome to GeeksforGeeks!
Initializing instance variable: Instance variables can be initialized using constructor. Inside the constructor, the initial value to instance variables is provided which can be used further anywhere in the program.
Value of First instance variable is: GeeksforGeeks Value of Second instance variable is: Sudo Placement
- Private Classes in Ruby
- Ruby | Matrix cofactor() function
- Ruby Integer odd? function with example
- Ruby Integer div() function with example
- Ruby | Symbol to_s function
- Ruby | Set replace() function
- Ruby | Set reset() function
- Ruby For Beginners
- Ruby | Array Concatenation using (+) function
- Ruby | at() function
- Ruby Float to_r() method with example
- Ruby | Keywords
- Ruby | Exception Class and its Methods
- Ruby | String inspect Method
- Ruby | Numeric imaginary() function
- Ruby | Numeric i() function
- Ruby | Numeric fdiv() function
- Ruby | String hex Method
- Ruby | String include? Method
- Ruby | Hash each_pair() function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.