Ruby Classes and Modules: Difference between revisions
Jump to navigation
Jump to search
(No difference)
|
Revision as of 00:16, 2 February 2011
Class Example
class Test
def initialize(value)
@value = value
end
attr :value, true # true means a setter is created in addition to a getter
attr_accessor :height, :width # create setters and getters
end
t = Test.new(5)
puts "value is %d" % t.value
t.height, t.width = 20, 30
puts "height and width are %d and %d" % [t.height, t.width]
Module Example
module Dice
# virtual roll of a pair of dice
def roll
r1 = rand(6) + 1
r2 = rand(6) + 1
total = r1+r2
puts "You rolled %d and %d (%d)." % [r1, r2, total]
end
end
class Game
include Dice
end
g = Game.new
g.roll
Module Method Example
module Binary
def Binary.to_bin(num)
bin = sprintf("%08b", num)
end
end
puts Binary.to_bin(123) # 01111011
Counter Class Example
class Counter
def initialize
@counter = {}
@totalCount = 0
end
def add(object)
if not @counter.key? object
@counter[object] = 0
end
@counter[object] += 1
@totalCount += 1
end
def randomObject
index = rand(@totalCount)
keys = @counter.keys
i = 0
count = 0
key = keys[i]
while count <= index
count += @counter[key]
key = keys[i]
i += 1
end
return key
end
def size
return @totalCount
end
end