Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Ruby gem or library that provides a way to parse ordinal numbers?

Tags:

ruby

gem

I'm looking for a way to parse ordinal numbers (first, second, third, etc) in Ruby and convert them to integers. Do you know of any libraries that do this?

like image 295
Ajedi32 Avatar asked Nov 02 '12 19:11

Ajedi32


2 Answers

I was half-way through asking this question when I realized that the chronic gem does this as part of the process of parsing dates. After installing the gem, you can convert ordinal numbers to integers pretty easily:

irb(main):001:0> require 'chronic'
=> true
irb(main):002:0> Chronic::Numerizer.numerize("eighty-fifth").to_i
=> 85

Edit: Unfortunately, it seems that chronic doesn't correctly parse the ordinal "second":

irb(main):003:0> Chronic::Numerizer.numerize("twenty-second").to_i
=> 20

The reason for this is that chronic is designed to parse dates and times, and "second" could be either an ordinal number or a unit of time in that context. To solve this problem, you can monkey patch chronic's Numerizer class with this line:

Chronic::Numerizer::ORDINALS.insert(1, ['second', '2'])

Now it works:

irb(main):005:0> Chronic::Numerizer.numerize("eighty-second").to_i
=> 82

If you are actually using chronic for its intended purpose though, you probably won't want to screw with its internals. In that case, you can copy the source code from Chronic::Numerizer into a new class and use that one instead. Don't forget to add ['second', '2'] to the ORDINALS constant in the new class.

like image 148
Ajedi32 Avatar answered Nov 12 '22 20:11

Ajedi32


There's a gem called numerouno which seems to be specifically targeted at this, if Chronic doesn't fit your use case.

like image 26
Chris Heald Avatar answered Nov 12 '22 19:11

Chris Heald