Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Given @Comments - how to obtain the 2nd to last comment w/o rehitting the db

Tags:

given @comments which can contain 1 or more records. How do I obtain the 2nd to last comment?

Thanks

like image 579
AnApprentice Avatar asked Jan 16 '11 19:01

AnApprentice


2 Answers

I suppose that would also be called the penultimate record:

@comments[-2] 

Here are the docs1 to Ruby's interesting index operator.


1. Rubyists, note how I linked this. If you take the version out of your ruby-doc links the reference will be durable and recent.
like image 118
DigitalRoss Avatar answered Oct 27 '22 00:10

DigitalRoss


With any Ruby array, you can specify any range or specific index, for example if you wanted every comment from the second oldest to the second newest you could do like:

@comments[1..-2] 

And to get just the second to last:

@comments[-2] 

Documentation for Ruby Array#range

In Rails, if you wanted the last two comments, then you could do this, which returns an array of the last two:

@comments.last(2) 

Documentation for ActiveRecord::FinderMethods

like image 30
koanima Avatar answered Oct 27 '22 00:10

koanima