Instructions
Create a function first_and_last that takes an array and returns
a new array containing only the first and last elements.
Example: first_and_last([1, 2, 3, 4]) returns [1, 4]
Hints:
- Use array.first and array.last
- Return a new array with [first, last]
- Handle edge cases like empty arrays
Your Code
def first_and_last(arr) [arr.first, arr.last] end
RSpec.describe "first_and_last" do
it "returns first and last of [1,2,3,4]" do
expect(first_and_last([1, 2, 3, 4])).to eq([1, 4])
end
it "returns same element twice for single item" do
expect(first_and_last([5])).to eq([5, 5])
end
it "works with strings" do
expect(first_and_last(["a", "b", "c"])).to eq(["a", "c"])
end
end
Results
Click "Run Tests" to see results
1 / 6
Next: Double Each