Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Just for demo. DON'T DO THIS IN PRODUCTION CODE.
- class MyComplex
- def initialize(real=0, imag=0)
- @real = real
- @imag = imag
- end
- def +(other)
- class_name = self.class
- result = class_name.new
- case other
- when result.class
- result.real = self.real + other.real
- result.imag = self.imag + other.imag
- else
- result.real = self.real + other
- result.imag = self.imag
- end
- result
- end
- def real
- return @real
- end
- def real=(num)
- @real = num
- end
- def imag
- return @imag
- end
- def imag=(num)
- @imag = num
- end
- def to_s
- real_str = @real.to_s
- imag_str = @imag >= 0 ? '+' + @imag.to_s : @imag.to_s
- real_str + imag_str + 'i'
- end
- end
- [Fixnum, Bignum, Float].each do |klass|
- eval <<-END
- class #{klass}
- alias_method :plus, :+
- def +(other)
- if other.is_a? MyComplex
- class_name = other.class
- result = class_name.new
- result.real = self.plus(other.real)
- result.imag = other.imag
- return result
- else
- self.plus(other)
- end
- end
- end
- END
- end
- if __FILE__ == $0
- a = MyComplex.new 3, 4
- b = MyComplex.new 4, 3
- puts a + b
- puts a + 2
- puts 2 + a
- puts 3.2 + a
- puts (2**100) + a
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement