I don't know any documentation about exactly what Kernel#rand expects from the Range argument, but can we see what happens by overriding respond_to? in your class and then watching how things fall apart:
def respond_to?(m) puts "They want us to support #{m}" super end
Doing this tells us that rand wants to call the #- and #+ methods on your Int instances. This makes sense, considering that rand(a..b) designed to work with integers.
Thus, we throw fast dirty implementations of addition and subtraction:
def -(other) self.class.new(to_int - other.to_int) end def +(other) self.class.new(to_int + other.to_int) end
and we start getting rand Int from our calls to rand .
I donβt know where (or if) this is documented, so you have to excuse me a little wave of the hand. I usually spend some time using the Ruby source code to answer this question, but now I don't have enough time.
source share