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] }
The tr() is an inbuilt method in Ruby returns the trace i.e., sum of diagonal elements of the matrix. Syntax: mat1.tr() Parameters: The function needs the matrix whose trace is to be returned.
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.
there is even simpler solution
line.scan(/\d+/).first
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With