MxLDevs
MxLDevs

Reputation: 19506

Ruby: Treating a class like a number?

I want to mix roman numerals with arabic numerals when doing some math.

I would define some classes for each symbol

class I
end

class V
end

class X
end

Now I want to be able to say things like

5 + V   # results in 10
X + 12  # results in 22

But am not sure where to start.
I would have to define a method that tells ruby how 5 + V works, give each class a value, and when I say

I

I should get the value 1.

What kind of methods should I look at that allows me to treat X as the number 10?

Upvotes: 1

Views: 110

Answers (2)

Mischa
Mischa

Reputation: 43298

Seems really simple to me:

V = 5
V + 1 #=> 6

If you want to show the result as roman numerals, I would extend the Fixnum class with a to_roman method:

class Fixnum
  def to_roman
    # I'll leave the implementation up to you
  end
end

With this you can do:

10.to_roman #=> "X"

Upvotes: 6

allaire
allaire

Reputation: 6045

You could overwrite the + operator in your roman class, so that would works for X + 12, but not for 12 + X. See this blog post: http://strugglingwithruby.blogspot.ca/2010/04/operator-overloading.html for more infos

See

The definition is not commutative, i.e., trying to do 3 + a would fail. To get that to work you would need to override the addition method in Integer - and I think that would be a bad idea.

Upvotes: 0

Related Questions