given @comments which can contain 1 or more records. How do I obtain the 2nd to last comment?
Thanks
I suppose that would also be called the penultimate record:
@comments[-2]
Here are the docs1 to Ruby's interesting index operator.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With