118

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]?

2 Answers 2

236

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
Sign up to request clarification or add additional context in comments.

3 Comments

Let's not forget the convenient Array#last, too :) [1,2,3].last #=> 3
@theTinMan Since pop also modifies the array, it's not what was asked for here.
Also that while a.last = 10 #=> NoMethodError: undefined method last=' but a[-1] = 10 works as intended.
13

One other way, using the splat operator:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.