Simulating a Subclass of Fixnum
require 'delegate'
class HexNumber < DelegateClass(Fixnum)
# The string representations of this class are hexadecimal numbers.
def to_s
sign = self < 0 ? "-" : ""
hex = abs.to_s(16)
"#{sign}0x#{hex}"
end
def inspect
to_s
end
end
HexNumber.new(10) # => 0xa
HexNumber.new(-10) # => -0xa
HexNumber.new(1000000) # => 0xf4240
HexNumber.new(1024 ** 10) # => 0x10000000000000000000000000
HexNumber.new(10).succ # => 11
HexNumber.new(10) * 2 # => 20
Related examples in the same category