Skip to content

Instantly share code, notes, and snippets.

@paulbellamy
Created December 13, 2012 10:29
Show Gist options
  • Save paulbellamy/4275579 to your computer and use it in GitHub Desktop.
Save paulbellamy/4275579 to your computer and use it in GitHub Desktop.
A static typing system for ruby in ruby
$ ruby types_usage.rb
Fermenting the cheese for 5 days!
Fermenting the cheddar for 0.5 days!
./types.rb:7:in `types': Expected #<Walrus:0x7f7e71bb4328> to be a Cheese, but was a Walrus (ArgumentError)
from types_usage.rb:1:in `each'
from types_usage.rb:1:in `each_slice'
from ./types.rb:5:in `each'
from ./types.rb:5:in `each_slice'
from ./types.rb:5:in `each'
from ./types.rb:5:in `types'
from types_usage.rb:22:in `ferment'
from types_usage.rb:28
class Object
def types(*args)
raise ArgumentError.new("types must have an even number of arguments") unless args.length.even?
args.each_slice(2).each do |type, value|
unless value.is_a?(type)
raise ArgumentError.new("Expected #{value.inspect} to be a #{type}, but was a #{value.class}")
end
end
end
end
require 'types'
class Cheese
def name
"cheese"
end
end
class Cheddar < Cheese
def name
"cheddar"
end
end
class Walrus
def name
"Bill"
end
end
def ferment(cheese, days)
types Cheese, cheese,
Numeric, days
puts "Fermenting the #{cheese.name} for #{days} days!"
end
ferment Cheese.new, 5
ferment Cheddar.new, 0.5
ferment Walrus.new, 10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment