There has been an astounding amount of invective and discussion over a recent addition to Rails. Briefly, if you have an array in Rails, you can now use ordinal numbers to get at the first ten members through aliases such as Array#second, Array#third, and so on. Some people are concerned about code bloat, some are concerned about lack of elegance, and DHH’s judgment in writing this bit of code has been seriously challenged.
Well, I’m not happy either - because the changes don’t go far enough. Let’s add one more method to Array and be done with it:
Class Array
def by_ordinal(pos)
self[pos.to_i - 1]
end
end
With this simple addition, you can refer to Array.by_ordinal("3rd"), Array.by_ordinal("21st"), or even Array.by_ordinal("407th"). As a bonus, the naming of the individual members is consistent with Rails’ Inflector#ordinalize method. Please join me in pushing for this to be included in Rails core.


10 comments
Comments feed for this article
November 20, 2008 at 4:17 pm
Chris Sutton
I like the new ordinal aliases.
I just wish I had a language that could handle that kind of extension in my dev stack. We’ll see how IronRuby turns out.
November 20, 2008 at 5:25 pm
Scott Becker
In my opinion, array[1] is fine, and much shorter than array.by_ordinal(”2nd”).
By the way, your code above is slightly wrong. Go into IRB and paste in the above code and then paste this:
[1,2,3].by_ordinal(”2nd”) # => 3
If you really want this, you probably want:
class Array
def by_ordinal(pos)
self[pos.to_i - 1]
end
end
November 20, 2008 at 5:31 pm
Mike Gunderloy
Correction noted. Obviously, I should have written tests first. Bad developer, no biscuit.
November 20, 2008 at 6:49 pm
Ivan V.
Mike, are you serious? I can’t tell if this is a joke or not… It’s one thing to have Model.first (really handy), and another to have array.first instead of just array[0]… and array.by_ordinal ? Please tell me you’re joking.
PS: I can see how this *could* be useful for the business analyst type (the concept of a count starting at “0″ is strange for some people)… but still…
November 21, 2008 at 2:23 am
Ryan Bigg
Mike, you noted the correction and didn’t fix it?
November 21, 2008 at 7:29 am
Mike Gunderloy
Oh, OK, I fixed it. But someone else can write the unit tests. I’m too laz… I mean, this is a community, isn’t it? Love and peace and contributing to code and all that?
November 21, 2008 at 10:06 am
Curt Hagenlocher
Brilliant satire!
November 21, 2008 at 12:16 pm
SeanG
Is this what you Rails people talk about?
November 22, 2008 at 6:49 pm
Ryan Bigg
Stuff like this should be moved to a plugin. Yes, it could be useful, but in certain applications it’s just additional overhead.
November 24, 2008 at 7:06 pm
Anonymous
Does Ruby have the equivalent of .net extension methods? No change to core needed in that case.