CS 330 Lecture 39 – Mixins and Wrap-up

Agenda

  • what ?s
  • multiple inheritance in Ruby?
  • implementing Orderable
  • wrap-up

Code

vec3.rb

module Comparable
  def < other
    (self <=> other) < 0
  end

  def > other
    (self <=> other) > 0
  end

  def <= other
    !(self > other)
  end

  def >= other
    !(self < other)
  end

  def == other
    (self <=> other) == 0
  end

  def != other
    !(self == other)
  end

  def between?(lo, hi)
    lo <= self && self < hi
  end
end

class Vector3
  include Comparable

  attr_reader :xyz

  def initialize(*args)
    if args.length == 0
      @xyz = [0, 0, 0]
    else
      @xyz = [args[0], args[1], args[2]]
    end
  end

  def [] i
    @xyz[i]
  end

  def []=(i, value)
    @xyz[i] = value
  end

  def to_s
    xyz.to_s
  end

  def <=> other
    @xyz <=> other.xyz
  end
end

a = Vector3.new
b = Vector3.new(1, 2, 3)
puts a, b
puts a <=> b
puts a < b
puts a > b
puts a == b
puts a != b
puts Vector3.new(1, 1, 1).between?(a, b)

Haiku

What’s the best language?
There’s no good answer to that
Chuck Norris’s fist

Comments

  1. Jake E says:

    In assembly, a common error is a seg fault without direction to what line it derived from. What might be a good way to figure out the occurrence of such a bug?

Leave a Reply

Your email address will not be published. Required fields are marked *