Back to home

Simple ExampleLinked List Example
Ruby Constructors main image

Ruby Constructors

The important constructor method is the initialize method.

Simple Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 # Ruby program to initialize instance # variable using constructor #!/usr/bin/ruby # class name class Geeks # constructor def initialize # instance variable intialzation @inst_1 = "GeeksforGeeks" @inst_2 = "Sudo Placement" end # display method def display puts "Value of First instance variable is: #{@inst_1}" puts "Value of Second instance variable is: #{@inst_2}" end end # creating object obj1 = Geeks.new() # calling display method obj1.display()

Linked List Example

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 """ Basic implementation without all methods """ class LinkedList def initialize(head=nil) if head.nil? @size = 0 else @size = 1 end @head = head end def getSize @size end def insertFirst(n) if @head.nil? @head = n else tmp = @head @head = n n.setNext(tmp) end @size += 1 end def clear @head = nil @size = 0 end def getFirst @head end end class Node def initialize(data = nil) @data = data @next = nil end def getNext @next end def setNext(n) @next = n end end # test Ruby file begin gem 'minitest', '>= 5.0.0' require 'minitest/autorun' require_relative 'linked_list' rescue Gem::LoadError => e puts "\nMissing Dependency:\n#{e.backtrace.first} #{e.message}" puts 'Minitest 5.0 gem must be installed for the Ruby track.' rescue LoadError => e puts "\nError:\n#{e.backtrace.first} #{e.message}" puts DATA.read exit 1 end # Common test data version: 1.1.0 be3ae66 class LinkedListTest < Minitest::Test def test_get_size # skip n1 = Node.new(1) ll = LinkedList.new(n1) assert_equal 1, ll.getSize() end def test_insert_first # skip n1 = Node.new(1) n2 = Node.new(1) ll = LinkedList.new(n1) ll.insertFirst(n2) assert_equal 2, ll.getSize() end def test_clear # skip n1 = Node.new(1) n2 = Node.new(1) ll = LinkedList.new(n1) ll.insertFirst(n2) ll.clear() assert_equal 0, ll.getSize() assert_nil nil, ll.getFirst() end end __END__

Dennis O'Keeffe

@dennisokeeffe92
  • Melbourne, Australia

Hi, I am a professional Software Engineer. Formerly of Culture Amp, UsabilityHub, Present Company and NightGuru.
I am currently working on workingoutloud.dev, Den Dribbles and LandPad .

Related articles


1,200+ PEOPLE ALREADY JOINED ❤️️

Get fresh posts + news direct to your inbox.

No spam. We only send you relevant content.