The following code will work.
n = int 42
# =>42 is substituted
f = int 4.2
# => TypeError!
Monkey patch to the Kernel
module as follows
module Kernel
module_function
def int(var = 0)
if var.is_a?(Integer)
var
else
raise TypeError, "#{var} isn't Integer"
end
end
end
After that, you can create a Ruby variable like a type declaration just by writing n = int 42
. Also, if you pass a value of a different type (or class), TypeError
will occur as an exception.
n = int 42
i = int 21
p n
# => 42
p i
# => 21
n = int 4.2
# => `int': 4.2 isn't Integer (TypeError)
If you want to narrow the range of influence, you should write as follows in refinements
module Type
refine Kernel do
module_function
def int(var = 0)
if var.is_a?(Integer)
var
else
raise TypeError, "#{var} isn't Integer"
end
end
end
end
After that, if you use ʻusing Type` where you want to use it, it's OK.
For the time being, ʻIntegerand
String` can be written like a type declaration like this. Let's think about how to write Array or Hash.
Recommended Posts