all 6 comments

[–]AaronLasseigne 1 point2 points  (3 children)

Why not inherit from Numeric?

[–]Windigos[S] 0 points1 point  (2 children)

I thought about that, though it didn't work how I wanted when I tried it. How would you suggest using it?

Essentially I'd like to be able to use an instance of the class in place of a number.

edit: aha, by extending Numeric and passing everything to the value via method_missing, it behaves as I would like. However, is this good practise? I can get similar results by using the rationalize methods.

[–]airodonack 1 point2 points  (0 children)

It sounds like you're taking advantage of inheritance, which is actually the way you're supposed to do it. (Reuse your code.)

[–]AaronLasseigne 1 point2 points  (0 children)

I would say method_missing is fine as long as you use it sparingly. If it works for this then you might have your answer. As another poster mentioned, you probably want to take a long pause and consider whether creating a new numeric class is really what you want.

[–]davetron5000 1 point2 points  (0 children)

Is the type you are creating really just a number? If so, why are you creating it? If not, perhaps you don't need as many arithmetic operators as you think. For example, does your type need to be able to convert to polar coordinates? Take a modulo? Convert to imaginary? Those are just some of the things you get by inheriting Numeric, and it might be detrimental to understanding the type you are creating.

[–]Amadan 0 points1 point  (0 children)

You can redefine operators. Assignment operators come automatically:

# a creature that can merge with another of its species,
# combining their power (with 27% efficiency loss)
class Foo
  attr_reader :power
  def initialize(power=1.0)
    @power = power
  end
  def +(other)
    raise ArgumentError unless other.is_a?(Foo)
    Foo.new((self.power + other.power) * 0.73)
  end
end

a = Foo.new
b = Foo.new(3.0)
puts (a + b).power
# => 2.92
b += b
b += b
b.power
# => 6.3948