Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract number from string in Ruby

Tags:

ruby

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]  } 
like image 793
OscarRyz Avatar asked Apr 14 '10 20:04

OscarRyz


People also ask

What is TR in Ruby?

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.


2 Answers

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.

like image 57
Amit Patel Avatar answered Oct 11 '22 09:10

Amit Patel


there is even simpler solution

line.scan(/\d+/).first 
like image 31
binarycode Avatar answered Oct 11 '22 10:10

binarycode