Instructions
Create a function first_two that uses pattern matching to extract
the first two elements from an array.
Use the in pattern matching syntax:
ruby
case array
in [first, second, *rest]
# use first and second
end
Return an array with just the first two elements.
Hints:
- Use case/in for pattern matching
- Use [a, b, *] to match first two and ignore rest
- Return [a, b]
Your Code
def first_two(array)
case array
in [a, b, *]
[a, b]
in [a]
[a, nil]
in []
[nil, nil]
end
end
RSpec.describe "first_two" do
it "extracts first two from longer array" do
expect(first_two([1, 2, 3, 4])).to eq([1, 2])
end
it "works with exactly two elements" do
expect(first_two([5, 6])).to eq([5, 6])
end
it "handles single element" do
expect(first_two([1])).to eq([1, nil])
end
it "handles empty array" do
expect(first_two([])).to eq([nil, nil])
end
end
Results
Click "Run Tests" to see results