I\'m using this code:
s = line.match( /ABCD(\\d{4})/ ).values_at( 1 )[0]
To extract numbers from strings like:
ABCD1234
AB
a.map {|x| x[/\d+/]}
There are many Ruby ways as per http://www.ruby-forum.com/topic/125709
line.scan(/\d/).join('')
line.gsub(/[^0-9]/, '')
line.gsub(/[^\d]/, '')
line.tr("^0-9", '')
line.delete("^0-9")
line.split(/[^\d]/).join
line.gsub(/\D/, '')
Try each on you console.
Also check the benchmark report in that post.
The simplest and fastest way is to just get all integers out of the string.
str = 'abc123def456'
str.delete("^0-9")
=> "123456"
Comparing benchmarks on a long string with some of the other solutions provided here, we can see this is orders of magnitude faster:
require 'benchmark'
@string = [*'a'..'z'].concat([*1..10_000].map(&:to_s)).shuffle.join
Benchmark.bm(10) do |x|
x.report(:each_char) do
@string.each_char{ |c| @string.delete!(c) if c.ord<48 or c.ord>57 }
end
x.report(:match) do |x|
/\d+/.match(@string).to_s
end
x.report(:map) do |x|
@string.split.map {|x| x[/\d+/]}
end
x.report(:gsub) do |x|
@string.gsub(/\D/, '')
end
x.report(:delete) do
@string.delete("^0-9")
end
end
user system total real
each_char 0.020000 0.020000 0.040000 ( 0.037325)
match 0.000000 0.000000 0.000000 ( 0.001379)
map 0.000000 0.000000 0.000000 ( 0.001414)
gsub 0.000000 0.000000 0.000000 ( 0.000582)
delete 0.000000 0.000000 0.000000 ( 0.000060)
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
your_input = "abc1cd2"
your_input.split(//).map {|x| x[/\d+/]}.compact.join("").to_i
This should work.
there is even simpler solution
line.scan(/\d+/).first