For practice I tried implementing a bubble sort algorithm in Ruby. I'm especially interested in creating clean DRY and KISS code and keeping things readable, but efficient. Any hints to improve things would be very much appreciated. The code looks like this:
class Sorter
def initialize
end
def sort(stack)
if stack.length == 0
return stack
else
checkArguments(stack)
if stack.length == 1
return stack
else
newstack = []
stackIsSorted = false
while !stackIsSorted
newstack = iterateThroughStack(stack)
if newstack == stack
stackIsSorted = true
else
stack = newstack
end
end
return newstack
end
end
end
def checkArguments(stack)
stack.each do
|element|
if element.class != Float && element.class != Fixnum
raise ArgumentError, "element detected in stack that is not an integer or double"
end
end
end
def iterateThroughStack(stack)
newstack = []
currentElement = stack[0]
for i in (1...stack.length)
if currentElement < stack[i]
newstack.push(currentElement)
currentElement = stack[i]
else
newstack.push(stack[i])
end
end
newstack.push(currentElement)
end
end
Then, after reading about Test Driven Development, I started using this practice and since then, I think code makes more sense with unit tests. So below are the unit test I wrote:
require 'test/unit'
require 'lib/Sorter'
class Test_Sorter < Test::Unit::TestCase
def setup
@sorter = Sorter.new
end
def test_emptyStack
stack = []
assert_equal(stack, @sorter.sort(stack), "sorting empty stack failed")
end
def test_StackWithOneElement
stack = [1]
assert_equal(stack, @sorter.sort(stack), "sorting stack with one element: 1 failed")
stack = ["a"]
assert_raise (ArgumentError) { @sorter.sort(stack) }
end
def test_StackWithTwoElements
stack = [2, 1]
sorted_stack = [1, 2]
assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with two elements: 1, 2 failed")
stack = [2, "a"]
assert_raise (ArgumentError) { @sorter.sort(stack) }
end
def test_StackWithThreeElements
stack = [2, 3, 1]
sorted_stack = [1, 2, 3]
assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with three elements: 1, 2, 3 failed")
end
def test_StackWithFourElements
stack = [4, 2, 3, 1]
sorted_stack = [1, 2, 3, 4]
assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with four elements: 1, 2, 3, 4 failed")
end
end