How to obtain the 2nd to last element o penultimate record.

A negative index is assumed to be relative to the end of the array---that is, an index of -1 indicates the last element of the array, -2 is the next to last element in the array, and so on.

Check these examples:

# Teaching Example
irb(main):001:0> a = [1, 2, 3]  
=> [1, 2, 3]
irb(main):002:0> a[-2]  
=> 2
# Practical Example
@order.line_items[-2]

Easy way to get the penultimate record

You can found more detailed info here Ruby Docs

Victor Velazquez

Coder, Musician, Startups, Passionate Dancer & Life Lover. Software Engineer at MagmaLabs, Co-founder of Web Dev Talks, Co-founder of Voltaire, Co-founder of Paqkit, Ex-co-founder of Zaznova.

Subscribe to The zazvick's blog

Get the latest posts delivered right to your inbox.

or subscribe via RSS with Feedly!