How to get the last element of an array in Ruby?

RubyArrays

Ruby Problem Overview


Example:

a = [1, 3, 4, 5]
b = [2, 3, 1, 5, 6]

How do I get the last value 5 in array a or last value 6 in array b without using a[3] and b[4]?

Ruby Solutions


Solution 1 - Ruby

Use -1 index (negative indices count backward from the end of the array):

a[-1] # => 5
b[-1] # => 6

or Array#last method:

a.last # => 5
b.last # => 6

Solution 2 - Ruby

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRails beginnerView Question on Stackoverflow
Solution 1 - RubyKL-7View Answer on Stackoverflow
Solution 2 - RubyLewis BuckleyView Answer on Stackoverflow