I need to create a method named first_and_last. It should use one argument, an Array, and return a new Array with only the first and last objects of the argument.
Here is what I have so far, but the method seems to ignore the initial argument and just create a new array.
def first_and_last(a)
arr = Array.new
arr = ["a", "b", "c"]
end
You can use the values_at()
method to get the first and last elements in an array like this:
def first_and_last(input_array)
input_array.values_at(0,-1)
end
Depending on what behavior you're looking for, it might not work on arrays with 1 or 0 elements. You can read more about the method here.
You can also use .first for the first element in the array, and .last for the last element in an array.
def first_and_last(arr)
[arr.first, arr.last]
end
p first_and_last([1,2,3,4,5,6])
Or....
def first_and_last(arr)
[arr[0], arr[-1]]
end
p first_and_last([1,2,3,4,5,6])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With