Friday, November 20, 2009

It's RUBY time :) - Strongly typed arraylists in Ruby

Hey Guys,

I was trying out Ruby and in the program below I am attempting to create a strongly typed ArrayList :) Seriously, I really really enjoy programming in Ruby :) Let me know if you have any comments...!



# Author - Karthik Ananthapadmanaban
# Date/Time - 11/21/2009 1.43 AM
# Updated on - 11/21/2009 11.21 AM

# A simple module that encrypts/decypts strings
# Similar to caesar's cipher
module Crypt
class Cryptor
def Encrypt(string)
@str1 = ""
string.each_byte{|x| @str1 = @str1 + ((x+1).chr)}
return @str1
end

def Decrypt(string)
@str1 = ""
string.each_byte{|x| @str1 = @str1 + ((x-1).chr)}
return @str1
end
end
end

# A simple module that implements
# various arithmetic operations
module Math
class Arithmetic
def Add(num1,num2)
return num1+num2
end

def Sub(num1,num2)
return num1-num2
end

def Mul(num1,num2)
return num1*num2
end

def Div(num1,num2)
return num1/num2
end

def Sqr(num1)
return num1*num1
end

def Sqrt(num1)
return num1 ** 0.5
end
end
end

# As we all know, ruby is dynamically typed
# I just wanted to create a class
# that allows only manipulating a certain type
# so, the result is a strongly typed class (trivially?) :)
# Yes, in C# ArrayList items are not strongly typed,
# against List<>, where the items are strongly typed <>
# comments are welcome ;)
module Collections
class ArrayList
def initialize (defType)
@defaultType = defType
@objArr = []

@posIndex = 0
end

def Add(someObj)
if (someObj.class.to_s.eql?(@defaultType))
puts("Adding the object")
@objArr.push(someObj)
else
puts("Not adding the object")
end
end

def Get
return @objArr
end

# Why don't you just use Array.At? :)
def GetItemAt(pos)
for obj in @objArr

if (@posIndex == pos.to_i)
@posIndex = 0
return obj
else
@posIndex = @posIndex +1
end
end
end
end
end

include Crypt
include Math
include Collections

cr = Cryptor.new
puts(cr.Encrypt("this is a very very very long string"))
puts(cr.Decrypt(cr.Encrypt("this is a very very very long string")))

puts("\n")

m1 = Arithmetic.new
m2 = Arithmetic.new
m3 = Arithmetic.new
m4 = Arithmetic.new
m5 = Arithmetic.new

# coll = ArrayList.new("Math::Arithmetic")
# or
coll = ArrayList.new(m1.class.to_s)

# All of the following would be added
coll.Add(m1)
coll.Add(m2)
coll.Add(m3)
coll.Add(m4)
coll.Add(m5)

puts("\n")

# This wouldn't be added
coll.Add(cr)

puts("\n")

i = 10

for obj in coll.Get
puts(obj.Add(4,i))
i = i+1
end

puts("\n")

puts("Number of items: ")
puts(coll.Get.length)

puts("\n")

# This would work
obj = coll.GetItemAt(3)
puts(obj.Add(4,10))

puts("\n")

# This wouldn't work
# As the obj would be undefined, an error would be
# generated at the top
obj = coll.GetItemAt(30)
puts(obj.Add(4,10))



Thanks and Happy coding :)

No comments: