Skip to content

Instantly share code, notes, and snippets.

@fabioyamate
Created October 11, 2013 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabioyamate/6928121 to your computer and use it in GitHub Desktop.
Save fabioyamate/6928121 to your computer and use it in GitHub Desktop.
type checking
# gem install mar
# this only checks at runtime, so it doesn't verify the type at compilation
require 'mar'
def type_check(type, value)
value.is_a?(type) or raise "#{value} is not type of #{type}"
end
def type_signature(*types)
->(original, *args, &blk) do
types[0..-2].zip(args).each do |(type, arg)|
type_check(type, arg)
end
result = original.call(1, 2, &blk)
type_check(types[-1], result)
result
end
end
class Foo
_ type_signature(Integer, Integer, Integer)
def foo(one_arg, two_arg)
one_arg + two_arg
end
end
puts Foo.new.foo(1, 2)
# => 3
puts Foo.new.foo(1, 'a')
# raises: a is not type of Integer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment