Instructions
Create a function describe_value that describes different types of values
using pattern matching.
Return:
- "empty array" for []
- "single: X" for array with one element (where X is the element)
- "pair: X, Y" for array with exactly two elements
- "many: N elements" for arrays with more than 2 elements
- "number: X" for integers
- "text: X" for strings
- "unknown" for anything else
Use type checking in patterns:
ruby
case value
in Integer => n
"number: #{n}"
in [a, b]
"pair"
end
Hints:
- Use Integer => n to match and bind integers
- Use String => s for strings
- Use [*rest] to capture remaining elements
Your Code
def describe_value(value)
case value
in []
"empty array"
in [x]
"single: #{x}"
in [x, y]
"pair: #{x}, #{y}"
in [*, *] => arr if arr.length > 2
"many: #{arr.length} elements"
in Integer => n
"number: #{n}"
in String => s
"text: #{s}"
else
"unknown"
end
end
RSpec.describe "describe_value" do
it "handles empty array" do
expect(describe_value([])).to eq("empty array")
end
it "handles single element array" do
expect(describe_value([42])).to eq("single: 42")
end
it "handles pair" do
expect(describe_value([1, 2])).to eq("pair: 1, 2")
end
it "handles many elements" do
expect(describe_value([1, 2, 3, 4])).to eq("many: 4 elements")
end
it "handles integers" do
expect(describe_value(42)).to eq("number: 42")
end
it "handles strings" do
expect(describe_value("hello")).to eq("text: hello")
end
it "handles unknown types" do
expect(describe_value(3.14)).to eq("unknown")
end
end
Results
Click "Run Tests" to see results