Create HexNumber : DelegateClass « Class « Ruby






Create HexNumber


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

puts HexNumber.new(10) * 2                         # => 20
puts HexNumber.new(10) + HexNumber.new(200)        # => 210

 








Related examples in the same category

1.Delegating Method Calls to Another Object