Instructions
Create a function parse_number that takes a string and returns
a parsed integer. Handle these cases:
- Valid number string: return the integer
- Invalid format: return
:invalid_format - Nil input: return
:no_input
Rescue multiple exception types:
ruby
begin
# code
rescue ArgumentError
# handle one type
rescue NoMethodError
# handle another
end
Hints:
- Use Integer(str) for strict parsing
- ArgumentError for invalid format
- NoMethodError when calling on nil
Your Code
def parse_number(str) Integer(str) rescue ArgumentError :invalid_format rescue TypeError, NoMethodError :no_input end
RSpec.describe "parse_number" do
it "parses valid numbers" do
expect(parse_number("42")).to eq(42)
expect(parse_number("-5")).to eq(-5)
end
it "returns :invalid_format for bad input" do
expect(parse_number("abc")).to eq(:invalid_format)
expect(parse_number("12.5")).to eq(:invalid_format)
end
it "returns :no_input for nil" do
expect(parse_number(nil)).to eq(:no_input)
end
end
Results
Click "Run Tests" to see results