Instructions
Create a function extract_numbers that takes a string and returns
an array of all integers found in that string.
Use Ruby's scan method with a regular expression:
ruby
"abc".scan(/pattern/) # Returns array of matches
The regex \d+ matches one or more digits.
Example:
```ruby
extract_numbers("I have 3 cats and 2 dogs")
=> [3, 2]
Hints:
- Use .scan(/\d+/) to find all digit sequences
- scan returns strings, use .map(&:to_i) to convert
- \d matches any digit, + means one or more
Your Code
def extract_numbers(str) str.scan(/\d+/).map(&:to_i) end
RSpec.describe "extract_numbers" do
it "extracts numbers from text" do
expect(extract_numbers("I have 3 cats and 2 dogs")).to eq([3, 2])
end
it "handles multiple digits" do
expect(extract_numbers("Order 123 has 45 items")).to eq([123, 45])
end
it "returns empty array when no numbers" do
expect(extract_numbers("no numbers here")).to eq([])
end
it "handles string with only numbers" do
expect(extract_numbers("42")).to eq([42])
end
it "handles adjacent numbers with text" do
expect(extract_numbers("a1b2c3")).to eq([1, 2, 3])
end
end
Results
Click "Run Tests" to see results