Last active
October 26, 2019 17:29
-
-
Save unak/9211261 to your computer and use it in GitHub Desktop.
type constraint
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
つまんないし名前が悪い。