Reputation: 215
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?
Upvotes: 0
Views: 51
Reputation: 2409
a[0,3]
means get 3 elements starting from offset 0.
Try this:
def lastFirst(a)
[a.first, a.last]
end
Upvotes: 5
Reputation: 118299
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]
Upvotes: 4