Extract number from string in Ruby

a.map {|x| x[/\d+/]}

there is even simpler solution

line.scan(/\d+/).first

There are many Ruby ways as per http://www.ruby-forum.com/topic/125709

  1. line.scan(/\d/).join('')
  2. line.gsub(/[^0-9]/, '')
  3. line.gsub(/[^\d]/, '')
  4. line.tr("^0-9", '')
  5. line.delete("^0-9")
  6. line.split(/[^\d]/).join
  7. line.gsub(/\D/, '')

Try each on you console.

Also check the benchmark report in that post.


The simplest and fastest way is use regular expression to parse the integers out from the string.

str = 'abc123def456' 

str.delete("^0-9")
=> "123456"

str.tr("^0-9","")
=> "123456"

Comparing benchmarks on a long string with some of the other solutions provided here, we can see tr is fastest with delete close 2nd.

require 'benchmark'

n = 2 
string = [*'a'..'z'].concat([*1..1_000_000].map(&:to_s)).shuffle.join

Benchmark.bmbm do |x|
  x.report('scan') do
    n.times {string.scan(/\d/).join}
  end
  x.report('gsub') do
    n.times {string.gsub(/[^\d]/,"")}
  end
  x.report('gsub2') do
    n.times {string.gsub(/\D/, '')}
  end
  x.report('tr') do
    n.times {string.tr("^0-9","")}
  end
  x.report('delete') do
    n.times {string.delete('^0-9')}
  end
  x.report('split') do
    n.times {string.split(/[^\d]/).join}
  end
end

Rehearsal ------------------------------------------
scan     3.509973   0.187274   3.697247 (  3.717773)
gsub     0.229568   0.002790   0.232358 (  0.233961)
gsub2    0.307728   0.013435   0.321163 (  0.390262)
tr       0.021395   0.000223   0.021618 (  0.022297)
delete   0.021290   0.002280   0.023570 (  0.024365)
split    0.284935   0.010274   0.295209 (  0.299865)
--------------------------------- total: 4.591165sec

             user     system      total        real
scan     3.146615   0.126009   3.272624 (  3.281860)
gsub     0.211263   0.001515   0.212778 (  0.213170)
gsub2    0.208482   0.000424   0.208906 (  0.209339)
tr       0.015228   0.000086   0.015314 (  0.015387)
delete   0.015786   0.000128   0.015914 (  0.016050)
split    0.205096   0.002736   0.207832 (  0.208380)

Tags:

Ruby