Ruby Classes and Modules

From Wiki
Jump to navigation Jump to search

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
    def to_s
        return @value
    end
end

t = Test.new(5)
puts t.value   # prints 5
puts t         # prints 5 (calls the to_s method)
t.height, t.width = 20, 30
puts "height and width are %d and %d" % [t.height, t.width]

Single inheritance:

class MyClass < SuperClass
    ...
end

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