#!/usr/bin/ruby ###################################################################### # BASIC CLASS SYNTAX class Person # < Object def initialize(name) @name = name end def greet(personName) "Hello, " + personName + ", my name is " + @name end def greetNobody "Hello, my name is " + @name end def accessUndefinedVariable @someVariableNameWeHaveNotDefined end end p = Person.new("Alice") print (p.greet("Bob") + "\n") print (p.accessUndefinedVariable.to_s + "\n") ###################################################################### # OPEN CLASSES # Initial declaration of Foo class Foo def bar "hi" end end f = Foo.new # Make a new Foo # In some other part of the source code... class Foo def baz "bye" end end print (f.baz + "\n") # Prints "bye" --- baz is defined ###################################################################### # OPERATOR OVERLOADING class Complex def initialize(r, i) @r = r @i = i end # Prefix negation def -@ Complex.new(-@r, @i) end # An ordinary named message with no arguments, whose name is - def - -self end # Binary message def -(other) Complex.new(self.r - other.r, self.i - other.i) end # Assignment syntax def r=(aNumber) @r = aNumber end def i=(aNumber) @i = aNumber end # Indexed assignment syntax def []=(anIndex, aNumber) if anIndex == 0 then @r = aNumber elsif anIndex == 1 then @i = aNumber end end def to_s '' + @r.to_s + '+' + @i.to_s + 'i' end end a = Complex.new(1, 2) b = -a c = a.- print (b.to_s + "\n") a.r = 3 a[1] = 4 print (a.to_s + "\n") ###################################################################### # ATTRIBUTES class Odd def initialize(a, b, c) @a = a @b = b @c = c end attr_reader :a # defines only method a attr_writer :b # defines only method b= attr_accessor :c # defines both c and c= end anOdd = Odd.new('hi', 'bye', '!') puts (anOdd.a + "\n") puts ((anOdd.b = 'hello') + "\n") anOdd.c += '!' puts (anOdd.c + "\n") ###################################################################### # MIXINS class Complex attr_accessor :r, :i def <=>(other) mySize = Math.sqrt(self.r * self.i) otherSize = Math.sqrt(other.r * other.i) return mySize <=> otherSize end include Comparable end c1 = Complex.new(1, 0) c2 = Complex.new(1, 2) less = c1 < c2 puts (less.to_s + "\n")