0

I'm doing some Ruby excercises. My goal is to create a method which reproduces the first and last number of an array.

My way of thinking was:

#create array
a = [1,2,3,4]
#create method
def lastFirst
   return a[0,3]
end
#call the method with an array
lastFirst(a)

But this produces [1,2,3] instead of what I want, which is (1,3).

Any thoughts on what I'm doing wrong?

2 Answers 2

5
a[0,3]

 means get 3 elements starting from offset 0.

Try this:

def lastFirst(a)
  [a.first, a.last]
end
Sign up to request clarification or add additional context in comments.

Comments

4

Write it using the Array#values_at method:

#create array
a = [1,2,3,4]
#create method
def last_first(a)
  a.values_at(0, -1)
end
#call the method
last_first(a) # => [1, 4]

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.