Back to home

Test fileLinked ListTesting
Ruby Linked List main image

Ruby Linked List

This requires the gem installation of minitest.

Test file

Create file linked_list_test.rb:

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 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__

Linked List

Create file linked_list.rb:

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

Testing

Change into directory and run ruby linked_list_test.rb.

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.