Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added Array#second through Array#tenth as aliases for Array#[1] throu…

…gh Array#[9] [DHH]
  • Loading branch information...
commit 22af62cf486721ee2e45bb720c42ac2f4121faf4 1 parent 7650ff8
David Heinemeier Hansson dhh authored
2  activesupport/CHANGELOG
View
@@ -1,5 +1,7 @@
*Edge*
+* Added Array#second through Array#tenth as aliases for Array#[1] through Array#[9] [DHH]
+
* Added test/do declaration style testing to ActiveSupport::TestCase [DHH via Jay Fields]
* Added Object#present? which is equivalent to !Object#blank? [DHH]
45 activesupport/lib/active_support/core_ext/array/access.rb
View
@@ -20,6 +20,51 @@ def from(position)
def to(position)
self[0..position]
end
+
+ # Equal to self[1]

What’s with the redundant comments?

Henrik Nyh
henrik added a note

mikehale: The redundant comments are likely for RDoc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
+ def second
+ self[1]
+ end
+
+ # Equal to self[2]
+ def third
+ self[2]
+ end
+
+ # Equal to self[3]
+ def fourth
+ self[3]
+ end
+
+ # Equal to self[4]
+ def fifth
+ self[4]
+ end
+
+ # Equal to self[5]
+ def sixth
+ self[5]
+ end
+
+ # Equal to self[6]
+ def seventh
+ self[6]
+ end
+
+ # Equal to self[7]
+ def eighth
+ self[7]
+ end
+
+ # Equal to self[8]
+ def ninth
+ self[8]
+ end
+
+ # Equal to self[9]
+ def tenth
+ self[9]
+ end
end
end
end
14 activesupport/test/core_ext/array_ext_test.rb
View
@@ -13,6 +13,20 @@ def test_to
assert_equal %w( a b c ), %w( a b c d ).to(2)
assert_equal %w( a b c d ), %w( a b c d ).to(10)
end
+
+ def test_second_through_tenth
+ array = (1..10).to_a
+
+ assert_equal array[1], array.second
+ assert_equal array[2], array.third
+ assert_equal array[3], array.fourth
+ assert_equal array[4], array.fifth
+ assert_equal array[5], array.sixth
+ assert_equal array[6], array.seventh
+ assert_equal array[7], array.eighth
+ assert_equal array[8], array.ninth
+ assert_equal array[9], array.tenth
+ end
end
class ArrayExtToParamTests < Test::Unit::TestCase

105 comments on commit 22af62c

Jacques Crocker

Really? Seriously?

DJ Davis

I must admit, I think this is a pretty useful change. :-)

Nikos Dimitrakopoulos

I’m not sure if this is useful or not, but isn’t this (and all the things like this) bloating the code base anyway?

Michael Klishin

Hey, they call Ruby on Rails “a little framework”, what did you expect?

Dmytro Shteflyuk

Oops.

<ul>
 <li><%= link_to videos.first.title, video_path(videos.first) %></li>
 <li><%= link_to videos.second.title, video_path(videos.second) %></li>
 <li><%= link_to videos.third.title, video_path(videos.third) %></li>
 <li><%= link_to videos.fourth.title, video_path(videos.fourth) %></li>
 <li><%= link_to videos.fifth.title, video_path(videos.fifth) %></li>
 <li><%= link_to videos.sixth.title, video_path(videos.sixth) %></li>
 <li><%= link_to videos.seventh.title, video_path(videos.seventh) %></li>
 <li><%= link_to videos.eighth.title, video_path(videos.eighth) %></li>
 <li><%= link_to videos.ninth.title, video_path(videos.ninth) %></li>
 <li><%= link_to videos.tenth.title, video_path(videos.tenth) %></li>

Aleksey Dmitriev

Hey, guys, could you add helpers up to 100? I need special helpers such as eighty_six and seventy_three too :)

We also should add method_missing to parse one_hundred_thousands_and_forty_nine to completely exclude numbers from Ruby code

Yaroslav Markin

So many smart and helpful people in this thread, with original comments.

Michael Koziarski
Owner

Gee guys, your helpful attitude astounds me. Here’s an idea, don’t use the methods and they won’t bug you.

If you really think 10 methods equals bloat, you’d better go and remove every class and method in your application! Let me give you a quick head start:

 

 def entire_app(url)
  case url
  when "/hello_world.txt"
    "Hello WORLD!"
  end
 end
 
Jinzhu

10 useless methods,another 10 useless methods,another 10 useless methods ……

Peter Marklund

+1 for this change

David Heinemeier Hansson
Owner

Haha. I’m honored by the attention of this commit! It reminds me of the good ol’ days where we debated whether pluralization was worth it. Or whether 1.second was good. Thanks for the memories ;).

This particular patch was born from the daily work I do administrating the applications at 37signals. A lot of the support work requires going into script/console and investigating various objects. In the console, I got sick of not being able to do people.second when I had a collection and knew I needed the second record. first and last was so nice and fluid, but if I needed second or third, I had to drop back to array access. Didn’t like that, so here you go.

Vojtech Salbaba

i completely agree with this commit, 3 of 5 my applications end with this as extension anyway.

Aizat Faiz

If you needed this so much, why not stuff this into ~/.irbrc instead? Then its global to all your consoles! Personally I think that would have been a much more appreciated solution rather than stuffing it into activesupport.

jorrel

I wanted ‘second’ when I’m iterating hashes. But ‘third’ to ‘tenth’ sugar doesn’t seem to taste that sweet. :)

Henrique G. Testa

+1 for this too. I always use Array#first and Array#last for arrays of size 2.

Ryan Bigg

Doesn’t anyone else think that typing array1 is faster than typing array.second? Surely by now it’s become natural.

August Lilleaas

I think the biggest problem with this is that when I see people.fifth in code, I won’t know what to do. Also, spotting people[4] is easier when skimming the code.

Then again, if the argument is that this was used a lot in console, it’s all good I guess.

David Heinemeier Hansson
Owner

I’ve actually also used it in code. It’s particularly useful for command parameters. Think ARGV.second, ARGV.third. But yeah, not something you’d use every day. My most common use is with the console.

David Heinemeier Hansson
Owner

Radar, you could make the same argument against the built-in first and last. They have 0 and [-1] equivalents. But the English versions read nicer. Ruby is full of stuff that merely improves on readability. I love that about the language.

Matthias Georgi

I guess, this is just a diss to all the LOC counters ;)

Reg Braithwaite

Would anyone prefer methods like caddr?

Michael Koziarski
Owner

perhaps cdaddaddr?

Alexander Balashov

Nice commit :). I suggest that those second…tenth methods to be added to ActiveRecord::Base as well so we could do just Person.second.

Bryce "BonzoESC" Kerley

@raganwald: http://github.com/ivey/carpark provides it

Peter Jaros

Re: LOC:


		[:second, :third, :fourth, :fifth, :sixth, :seventh, :eighth, :ninth, :tenth].each_with_index do |name, i|
			define_method(name) { self[i+1] }
		end

Et voila.

Dale Campbell

I think something like this should be included on a per-app basis, as opposed to being in core. How hard is it to just ‘cp array_stupid.rb ./lib’ for your projects?

-5 points for this, kthx.

kris

Commits like this push me closer to Merb.

Ian Eure

This is great, but could you please provide Japanese localization? It’s so much easier for me to use:

foo.二番目に, foo.第3, foo.第4

When I’m in the console instead of foo1, foo2…foo[N].

Thanks, I’d really appreciate it.

Matthias Georgi

@Peeja: your code will not show in the documentation.

Mase B.

Or you could have some fancy-fun and alias :n(st/th) for 0 to your heart’s content. Then you get people.1st people.2nd… people.100th. If you’re feeling particularly courageous, you could toss the sucker in method_missing, and be able to do people.53485th.

Mase B.

Though I suppose that would cause confusion, since people expect “first” to be the “0th”. Well boo to that. Start at 1.

Mase B.

Or, I could learn Ruby, and realize that you can’t start a method with a number.

Matthias Georgi

Seriously I cant understand the console use case. Typing the brackets is for me way faster than typing a method name, even with tab completion.

Diogo Lisboa

These methods are pointless. So are most method added for readability (Time.now instead of Time.new?). But I believe there are more important ways to spend our time, and more valuable discussions. Just leave it.

Eric Allam

Honestly the only arguments I can really see for being against this is the extra methods being in the Array#methods call, which I sometimes use in the console. But even then most of the time when I’m looking up a method I have a pretty good idea what its called so I usually end up doing #methods.grep /whatever/ anyways

Brennan Dunn

More pointless bloat for the docs. What’s next, revamping #succ to make ‘first’.next # => ‘second’ ?

Bryce "BonzoESC" Kerley

Can we get an alternate version for C users who think of arrays as a0 being the “zeroth,” a1 being “first,” etc.? I’d like the choice in my code.

Pete Nicholls

Sugar so sweet it makes my teeth ache.

Amos King

So what do things like this do to my load time, and my memory usage. I know that there was just the commit of using :only on resources to lower memory consumption of routes. Now that we saved that memory we can fill it with other things. I believe that I read an interview with you, David, where you were asked about what is going in the rails core in the next release and you said something along the lines of, ‘It is more like; what is coming out?’ Maybe that isn’t what I heard.

Chris Wanstrath

If GitHub had a Hall of Fame, this thread would be the first entry.

Ryan Bates

@defunkt lol, and this one could be second.

Matthew Lyon

@binarylogic people get worked up for two reasons: 1) it makes rails more complex 2) it widens the gap between rails and “real” ruby, and if you work with non-rails ruby quite frequently, that gap becomes really annoying.

kenny

This is awesome!! Do you think we can add in second_to_last, third_to_last… tenth_to_last??

A few times it was said that this was more for use in the console, which is a strong argument that it really shouldn’t be in the code base.

If you think Array1, Array2 aren’t readable maybe you should find a different hobby/profession.

Mark Turner

if you cannot discern between what ruby does and what rails adds then yes I can see it being a problem…. but maybe the problem is that you don’t know ruby well enough. Rails makes lots of stuff easier, and this just adds to the list.

Personally I don’t mind access to my arrays in that fashion. It makes sense and is pretty readable.

+4 Bonus points for making it even easier for my designer to handle small bits of code.

Chris Lloyd

I think we should paint it red.

http://www.freebsd.org/doc/en_US.ISO8859-1/books/faq/misc.html#BIKESHED-PAINTING

Robby Russell

Let the man have his cake. :-)

Amos King

Good point Chris. I like your answer.

tedhenry10

Rails 0.9 was better.

Bob Martens

Wait, am I wrong, or do you not have to use this if you don’t want to?

Ruy Asan

I love this patch.

Tim Andersen

On the bright side, Git lets you undo commits as if they never even happened.

Brian Lopez

for the love of god, you’re all spamming my github dashboard :P

Those of you who hate this patch and want to move to another framework, go ahead. There’s 10x more about to start using Rails anyway.

Those of you who love this patch (and still love rails with it, for that matter) – do you really need to justify yet another spoonful of sugar?

@dhh – keep up the good work, I personally don’t mind if there are a few more methods I can optionally use to make my life easier

Anil Wadghule

I think the kind of commit is really useful. But should it be part of framework or not, not very sure!

John Wyles

Why stop at ten? Why not make some dynamic methods for converting numerics to flattened strings so we can do this for all elements in the array? I for one welcome our new 30+ character representational format!

It is hard not to get excited about such a thing: hella_long_array.one_million_seven_hundred_fifty_five_thousand_two_hundred_sixty_third

Error: Unclosed “” tag.

Jan Xie

car, cadr, caddr, cadddr, caddddr, cadddddr ..

Elise Huard

@chrislloyd’s answer nails it.

Michael Koziarski
Owner

Honestly, guys, the amount of effort you’ve expended here rivals only the penis extension thread on trac.

@defunkt: You need to add a STFU button which closes a thread and tells people to take a walk, hug their loved ones, or read a book.

Matt Hooks

cough ibtl cough

Neil Henegan

“This is awesome!! Do you think we can add in second_to_last, third_to_last… tenth_to_last??” – lol

Jesse Crockett

Hi. Here is my first github comment. I love this change. It may not be “useful” in the Cartesian sense, but it does subtract some hurt. Love it!

yawningman

sweet….


highscores = HighScore.first(:conditions => {:game => "Killer Instinct"})
    
p highscores.first 
p highscores.second
p highscores.third 
p highscores.fourth
....

ELLIOTTCABLE

I’m not going to argue against this — this is essentially, at it’s core, Rails-ish. This is the very reason I don’t use Rails, and I know there’s many others who think like me. There’s a thin line between sugar (Ruby) and bloat (Rails), and it’s useless to complain about Rails crossing it. I agree that Chris should add a feature to GitHub just so he can close this thread and we can all get on with life /=

Fabio MA

I think some people should go back to Java, where such a crime would never be perpetrated.

Nikos Dimitrakopoulos

@defunkt: Ok, this commit is one of the reasons I’ve come to lurve github a little more! Don’t ever put a STFU button! (Although it would be useful – to be honest :D)

Matthew Rudy Jacobs

Yeah. I think this is great. A great discussion, a great argument.

I read the commit logs every day, but this just makes me happy in a way I never expected.

Thankyou Github.

James Urquhart

I suggest you also add the following methods:

second_from_last, third_from_last, fourth_from_last, fifth_from_last, sixth_from_last, seventh_from_last, eighth_from_last, ninth_from_last, and tenth_from_last.

Mike Gaffney

@DHH, as you said to me earlier on Lighthouse,

“While I applaud the effort, I think this is not really don’t enough to be worth a [commit] in Rails code. If you use this a lot, I would definitely recommend making a plugin out of it, though.” -DHH : http://rails.lighthouseapp.com/projects/8994/tickets/1303-scriptgenerate-library

NZKoz : these types of arguments are exactly why rails is a good framework, people are allowed to make comments on things they don’t like.

defunkt: keep it up.

Diego Carrion

I think it should be in a plugin, maybe with more other aliases

Trevor Turk

ActiveSupport::CoreExtensions::PradiptasRolodex?

Cayce Balara

I got into a discussion of this over lunch one day at RubyConf. I’m reminded of George Carlin’s rant about some religious schlub not liking what he heard on the radio. “The radio has two knobs, Reverend… one turns it off, and the other changes the channel!” In other words, if you don’t like it, don’t use it.

That being said, I can’t wait for someone to add #penultimate.

ELLIOTTCABLE

It’s not about “if you don’t like it, don’t use it”. It’s about it being bloat. It’d be nice if computers could download, upload, transfer, run, and keep in memory an infinite amount of code. They can’t. There’s tons of slightly useful things you could add to Ruby that would be kinda nice, but they’d also be yet more bloat – YMB. Such things shouldn’t be added to Rails.

Wait, what am I saying? This is what Rails is all about. Thar she blows, men! Man the harpoons!

ELLIOTTCABLE

On another note, this epic thread has spawned it’s own meta-commentary: http://tr.im/19fd?stackoverflow

Andy Delcambre

+ # Equal to self[10]
+ def eleventh
+   self[10]
+ end

Now it goes to eleventh.

Mark Turner

@elliottcable Comments about comments? I love the tubes sometimes.

Per Velschow

I think DHH is using a Danish keyboard. Typing brackets on a Danish keyboard is actually quite cumbersome. :)

Tore Darell

http://pastie.org/317766

Joking aside, I’ve sometimes typed users.second just because my brain thought it’d work, and yes, [ and ] are a bit of a PITA to type on non-US keyboards.

Matthias Georgi

Programmers should just use US keyboard layout.

Sam Figueroa

@georgi: Yes they should.

Ozgun Ataman

While I myself use similar patches on a per-app basis, these kinds of extensions are a pure bloat to what otherwise is a great framework.

I understand that Rails is all about agile programming, but there needs to be a level of elegance and succinct quality we should not be willing to go below.

James Chen

@ieure: We programmers from China also need these especially for testers: foo.第二, foo.第三, foo.第四…

Steven Talcott Smith

What a bunch of whiny bitches! I personally vote for .second_from_last or .next_to_last as well. Readability first. Keep it up.

Benjamin Atkin

I was curious how many comments there were, and rather than looking through my history, I started looking for this commit in the repository. I must say that the rails directory structure is well organized. Everything’s broken down into little bits. Nice use of include.

Dan Glegg

All my arrays have length of eleven, thus this change is useless to me.

Dan Glegg

oh yeah and

%w(second third fourth fifth sixth seventh eighth ninth tenth).each {|n| define_method…..

/facepalm

Florian Aßmann

This should be an initializer. -1

Henrik Nyh

Peeja, danski: When I saw this commit back in June, I liked about it that it didn’t involve metaprogramming. If it only spans 2–10, I find this more readable. Also good for RDoc.

Bryan Thompson

I wonder what Zed has to say about this.

“kris- Commits like this push me closer to Merb.”

+1, and I wonder if Rails could just be split into a Rails-Core and a Rails-More, as well as a Rails-More-dumb_array_methods_and_other_gibberish

Christopher

Let’s get Dave Thomas to give a RailsConf Keynote about how we should fork Rails for the people that don’t want convenience methods.

Bob Martens

I find this entire section of comments fascinating … the say the least.

Ben Cullen-Kerney

My only objection to this is that we already have myarray.at built into Ruby. It doesn’t start at zero if that sort of thing bothers you, it works no matter how large your array is, it’s less typing, and it doesn’t even require square brackets.

Henrik Nyh

bak: Array#at is zero-indexed.

Henrik Nyh

mikehale: The redundant comments are likely for RDoc.

Ben Cullen-Kerney

henrik: so it is. Don’t know where that blip came from.

ANDO Yasushi

Hi all, I pushed ahead with this idea: http://d.hatena.ne.jp/technohippy/20081121#1227285803

Pete Nicholls

@technohippy

Good god.

Alex

~/work/test_222>rails -v Rails 2.2.2 ~/work/test_222>cs Loading development environment (Rails 2.2.2) >> arr = [1,2,3,4,5,6,7,8,9,10] => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >> arr.first => 1 >> arr.second => 2 >> arr.third => 3 >> arr.fourth => 4 >> arr.fifth => 5 >> arr.sixth NoMethodError: undefined method `sixth’ for [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:Array from (irb):7 >> arr.seventh NoMethodError: undefined method `seventh’ for [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:Array from (irb):8 >> arr.eighth NoMethodError: undefined method `eighth’ for [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:Array from (irb):9 >> arr.ninth NoMethodError: undefined method `ninth’ for [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:Array from (irb):10 >> arr.tenth NoMethodError: undefined method `tenth’ for [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:Array from (irb):11

why ???

ps, cs command = ./script/console

David Heinemeier Hansson
Owner

Zhang: http://github.com/rails/rails/commit/e50530ca3ab5db53ebc74314c54b62b91b932389

Jing Dong

at least it’s readable

Justin Ko

I really like this. What’s wrong with more readable???

Dušan Maliarik

To DHH: stop programming, start writing poetry. you are too good for this Ruby thing, because replacing

dhh_dumbideas2
with
dhh_dumbideas.second
is the most stupid thing I’ve ever seen. It surely makes the code more readable as you have to read the word instead of a number. thumbs up , just please, don’t become a Ruby core developer
Dušan Maliarik

sorry: dhh_dumbideas1

Carsten Nielsen

skrat, I think you want dhh_dumbideas1 for the second item.

Carsten Nielsen

Oops, textile.

Miha Plohl

bla.blunth … did You all see http://kitschmaster.com. it is still built with Rails. I still do not know why, though. Rails is changing faster than my sons teeth are growing. I am continually being challenged to read fresh mostly unusable code. Is this a lack of real communication between all You Souls?

Does any of You guys think a blink about Ruby 4.0?

Edmund Salvacion

wait.. what's going on?

Trung Lê

@dhh I welcome such changes to make Rails more human readable, more convenient and more aesthetic..hold on wait, but the assertion test are not English readable at all, reconsidering minitest/spec?

Please sign in to comment.
Something went wrong with that request. Please try again.