A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/ruby/ruby-constructors/ below:

Ruby | Constructors - GeeksforGeeks

Ruby | Constructors

Last Updated : 24 Feb, 2023

A constructor is a special method of the class that gets automatically invoked whenever an instance of the class is created. Like methods, a constructor may also contain a group of instructions or a method that will execute at the time of object creation.

Important points to remember about Constructors:

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

Syntax:

class Class_Name

   def initialize(parameter_list)

   end

end

Example: 

Ruby
# A Ruby program to demonstrate
# the working of constructor

#!/usr/bin/ruby

# class name
class Demo

    # constructor
    def initialize
        puts "Welcome to GeeksforGeeks!"
    end

end

# Creating Object
Demo.new

Output:

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. 

Example: 

Ruby
# A Ruby program to demonstrate
# the working of constructor

#!/usr/bin/ruby

# class name
class Demo

    # constructor
    def initialize
        puts "Welcome to GeeksforGeeks!"
    end

end

# Creating Object
Demo.new

Output:

Value of First instance variable is: GeeksforGeeks
Value of Second instance variable is: Sudo Placement


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4