Advertisement
cwchen

Operator overloading demo in Ruby

Feb 10th, 2016
197
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Ruby 1.29 KB | None | 0 0
  1. # Just for demo.  DON'T DO THIS IN PRODUCTION CODE.
  2.  
  3. class MyComplex
  4.   def initialize(real=0, imag=0)
  5.     @real = real
  6.     @imag = imag
  7.   end
  8.  
  9.   def +(other)
  10.     class_name = self.class
  11.     result = class_name.new
  12.     case other
  13.     when result.class
  14.       result.real = self.real + other.real
  15.       result.imag = self.imag + other.imag
  16.     else
  17.       result.real = self.real + other
  18.       result.imag = self.imag
  19.     end
  20.     result
  21.   end
  22.  
  23.   def real
  24.     return @real
  25.   end
  26.  
  27.   def real=(num)
  28.     @real = num
  29.   end
  30.  
  31.   def imag
  32.     return @imag
  33.   end
  34.  
  35.   def imag=(num)
  36.     @imag = num
  37.   end
  38.  
  39.   def to_s
  40.     real_str = @real.to_s
  41.     imag_str = @imag >= 0 ? '+' + @imag.to_s : @imag.to_s
  42.     real_str + imag_str + 'i'
  43.   end
  44. end
  45.  
  46. [Fixnum, Bignum, Float].each do |klass|
  47.   eval <<-END
  48. class #{klass}
  49.     alias_method :plus, :+
  50.     def +(other)
  51.       if other.is_a? MyComplex
  52.         class_name = other.class
  53.         result = class_name.new
  54.         result.real = self.plus(other.real)
  55.         result.imag = other.imag
  56.         return result
  57.       else
  58.         self.plus(other)
  59.       end
  60.     end
  61.   end
  62. END
  63. end
  64.  
  65. if __FILE__ == $0
  66.   a = MyComplex.new 3, 4
  67.   b = MyComplex.new 4, 3
  68.   puts a + b
  69.   puts a + 2
  70.   puts 2 + a
  71.   puts 3.2 + a
  72.   puts (2**100) + a
  73. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement