Skip to content

Instantly share code, notes, and snippets.

@capitalist
Created March 31, 2015 15:00
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save capitalist/473543b7ea24d461d030 to your computer and use it in GitHub Desktop.
Save capitalist/473543b7ea24d461d030 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
def Inherits(*classes)
klass = Class.new classes.shift # inherit from the last clas
while refine_with = classes.shift # include the others as module refinements just so we can turn them into modules
klass.include Module.new { include refine(refine_with) { } }
end
klass
end
class TwoD
attr_accessor :width, :height
def area
width * height
end
end
class ThreeD
attr_accessor :depth
def area
# why can't i call super here
# this method is included in the generated base class for Cube via the anonymous mixin which includes the ThreeD refinement
width * height * depth
end
end
class Square < TwoD
def width= w
super
self.height = w
end
end
class Cube < Inherits(Square,ThreeD)
def width= w
super
self.depth = w
end
def area
super
end
end
s = Square.new
s.width = 4
puts "Square Area: #{s.area}"
c = Cube.new
c.width = 4
puts "Cube Area: #{c.area}"
@jcutrell
Copy link

This is super weird. But pretty cool.

@miguelsan
Copy link

multiple inheritance in ruby, cool!
apart from the fact that you are returning the cube volume, not the area ;)

@philiplambok
Copy link

Hahaha

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment