0
0
RubyHow-ToBeginner · 3 min read

How to Extract Numbers from String in Ruby Easily

In Ruby, you can extract numbers from a string using String#scan with a regular expression like /\d+/ to find all digit sequences. Then, convert these string numbers to integers with map(&:to_i) for numeric use.
📐

Syntax

The main method to extract numbers from a string is scan, which searches the string for matches of a pattern.

  • string.scan(/\d+/): Finds all groups of digits in the string.
  • map(&:to_i): Converts each found string number to an integer.
ruby
numbers = "abc123def456".scan(/\d+/).map(&:to_i)
puts numbers.inspect
Output
[123, 456]
💻

Example

This example shows how to extract all numbers from a string and convert them to integers for further use.

ruby
text = "Order 12 apples and 30 oranges."
numbers = text.scan(/\d+/).map(&:to_i)
puts "Extracted numbers: #{numbers}"
Output
Extracted numbers: [12, 30]
⚠️

Common Pitfalls

One common mistake is to use to_i directly on the whole string, which only converts the leading number and ignores the rest.

Wrong way:

"abc123def456".to_i  # returns 0 because string does not start with a number

Right way:

"abc123def456".scan(/\d+/).map(&:to_i)  # returns [123, 456]
📊

Quick Reference

Use scan(/\d+/) to find all numbers as strings, then map(&:to_i) to convert them to integers. This works for multiple numbers in a string.

MethodDescriptionExample
scan(/\d+/)Finds all digit sequences in string"abc123def".scan(/\d+/) #=> ["123"]
map(&:to_i)Converts string numbers to integers["123", "456"].map(&:to_i) #=> [123, 456]
to_iConverts string to integer (only leading digits)"123abc".to_i #=> 123

Key Takeaways

Use String#scan with /\d+/ regex to find all numbers in a string.
Convert extracted string numbers to integers with map(&:to_i).
Avoid using to_i on the whole string if numbers are not at the start.
scan returns an array of strings matching the pattern.
This method works well for multiple numbers inside any string.