Thursday
20Nov2008
A Modest Proposal
Thursday, November 20, 2008 at 10:02AM
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
Well, I'm not happy either - because the changes don't go far enough. Let's add one more method to
[sourcecode language='ruby']
Class Array
def by_ordinal(pos)
self[pos.to_i - 1]
end
end
[/sourcecode]
With this simple addition, you can refer to
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:[sourcecode language='ruby']
Class Array
def by_ordinal(pos)
self[pos.to_i - 1]
end
end
[/sourcecode]
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.

Reader Comments (9)
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.
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
Correction noted. Obviously, I should have written tests first. Bad developer, no biscuit.
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...
Mike, you noted the correction and didn't fix it?
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?
Brilliant satire!
Is this what you Rails people talk about?
Stuff like this should be moved to a plugin. Yes, it could be useful, but in certain applications it's just additional overhead.