views:

109

answers:

2

Rails has a nice function, ordinalize, which converts an integer to a friendly string representation. Namely 1 becomes 1st, 2 becomes 2nd, and so on. My question is how might one implement the inverse feature?

To be more general I'd like to handle both of the following cases:

>> s = "First"
>> s.integerize
=> 1
>> s = 1st
>> s.integerize
=> 1

I am looking for an smart way to do this as opposed to a giant lookup table or just hacking off the last two characters. Any ideas would be appreciated.

+6  A: 

to_i does essentially 1/2 of that:

"72nd".to_i
=> 72

It doesn't check validity, but if you need to fail on bad input like "72x", you can just re-ordinalize and compare to the original input string.

For parsing ordinal words, Wikipedia seems impressively helpful.

Ken
A: 

The first case is relatively hard - I'd say the smart way to do it is find someone who's already done it and use their code. If you can't find someone, the next smartest thing would probably be restating (or renegotiating) the problem so that it's not needed. Beyond that, I think you're into parser-writing...

The second case is as trivial as the to_i already offered. You could also use a regex, I suppose:

"1000000th".scan(/\d+/).first.to_i #=> 1000000
Mike Woodhouse