Skip to content

Instantly share code, notes, and snippets.

@unak
Last active October 26, 2019 17:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unak/9211261 to your computer and use it in GitHub Desktop.
Save unak/9211261 to your computer and use it in GitHub Desktop.
type constraint
class Module
class ConstraintError < TypeError; end
def where(meth, constraint)
m = Module.new do
define_method(meth) do |*args|
args.zip(constraint.keys.first) do |arg, t|
raise ConstraintError, "type #{t} is expected, but #{arg.inspect} is passed" unless arg.is_a?(t)
end
ret = super(*args)
t = constraint.values.first
raise ConstraintError, "type #{t} is expected, but #{ret.inspect} is returned" unless ret.is_a?(t)
ret
end
end
self.prepend m
end
end
class Foo
where def foo(n, s)
puts "#{s}: #{n}"
end, [Integer, String] => NilClass
end
f = Foo.new.foo(10, "A")
@unak
Copy link
Author

unak commented Feb 25, 2014

つまんないし名前が悪い。

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