问题
given @comments which can contain 1 or more records. How do I obtain the 2nd to last comment?
Thanks
回答1:
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.
回答2:
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
回答3:
can contain 1 or more records
This question is old, but for people coming to this now...
The other solutions will return nil if there is only one record. If you want to be sure to return a record use:
@comments.last(2)[0]
回答4:
@comments[-2]
This is pretty much the same as your last question.
回答5:
@comments = Comment.all #Gather all comments from DB, filter as necessary.
@comments[-2] #Second to last comment in array
来源:https://stackoverflow.com/questions/4707507/rails-given-comments-how-to-obtain-the-2nd-to-last-comment-w-o-rehitting-th