Extract number from string in Ruby

Ruby

Ruby Problem Overview


I'm using this code:

s = line.match( /ABCD(\d{4})/ ).values_at( 1 )[0] 

To extract numbers from strings like:

ABCD1234
ABCD1235
ABCD1236

etc.

It works, but I wonder what other alternative I have to to this in Ruby?

My code:

ids = [] 
someBigString.lines.each {|line|
   ids << line.match( /ABCD(\d{4})/ ).values_at( 1 )[0] 
}

Ruby Solutions


Solution 1 - Ruby

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.

Solution 2 - Ruby

there is even simpler solution

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

Solution 3 - Ruby

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

Solution 4 - Ruby

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)

Solution 5 - Ruby

your_input = "abc1cd2"
your_input.split(//).map {|x| x[/\d+/]}.compact.join("").to_i

This should work.

Solution 6 - Ruby

Another solution may be to write:

myString = "sami103"
myString.each_char{ |c| myString.delete!(c) if c.ord<48 or c.ord>57 } #In this case, we are deleting all characters that do not represent numbers.

Now, if you type

myNumber = myString.to_i #or myString.to_f

This should return a

Solution 7 - Ruby

To extract number part from a string use the following:

str = 'abcd1234'
/\d+/.match(str).try(:[], 0)

It should return 1234

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionOscarRyzView Question on Stackoverflow
Solution 1 - RubyAmit PatelView Answer on Stackoverflow
Solution 2 - RubybinarycodeView Answer on Stackoverflow
Solution 3 - Rubyglenn mcdonaldView Answer on Stackoverflow
Solution 4 - RubylacostenycoderView Answer on Stackoverflow
Solution 5 - RubyRohit PatelView Answer on Stackoverflow
Solution 6 - Rubyuser2380436View Answer on Stackoverflow
Solution 7 - RubyRajesh PaulView Answer on Stackoverflow