Parsing String Data

I am very new to Ruby and I have an issue that I cannot seem to
solve.

Parse a data string, excise four digits (non- adjoined) in the middle
of the string, and then assemble a second string using the data.

As an example, my fisrt string has text “Test Part 123 G 477”, I want to
assemble a new string “AABB123477”.

What I do not know how to do is parse the text to get the numbers. Once
having them I have had no problems assembling the new string.

Can you help with this?

On Tue, Nov 16, 2010 at 2:57 PM, Bob T. [email protected] wrote:

having them I have had no problems assembling the new string.

Can you help with this?

You can use String#split or a regex depending on the requirements:

irb(main):001:0> parts = “Test Part 123 G 477”.split(" ")
=> [“Test”, “Part”, “123”, “G”, “477”]
irb(main):002:0> parts[2]
=> “123”
irb(main):003:0> parts[4]
=> “477”

If you know the data is always separated by spaces and the number is
in the second and fourth places, this should work.

Jesus.

On Tue, Nov 16, 2010 at 3:57 PM, Bob T. [email protected] wrote:

having them I have had no problems assembling the new string.
If you’re only interested in the numbers, using scan is another option:

“Test Part 123 G 477”.scan(/\d+/)
=> [“123”, “477”]

HTH,
Ammar

“Jesús Gabriel y Galán” [email protected] wrote in post
#961831:

On Tue, Nov 16, 2010 at 2:57 PM, Bob T. [email protected] wrote:

having them I have had no problems assembling the new string.

Can you help with this?

You can use String#split or a regex depending on the requirements:

irb(main):001:0> parts = “Test Part 123 G 477”.split(" ")
=> [“Test”, “Part”, “123”, “G”, “477”]
irb(main):002:0> parts[2]
=> “123”
irb(main):003:0> parts[4]
=> “477”

If you know the data is always separated by spaces and the number is
in the second and fourth places, this should work.

Jesus.

Jesus,

Thank you, I cannot guarantee that the data will always be in the same
format, however I know that the length of the string is always the same.
Can I pase the string one character at a time, and apply a set of rules
to determine what data to use and what data to discard?

For example I know that I want to use only the numerical data and not
the alphabetic data. The simplest, though not elegant way I can think of
is to go one character at a time and determine if that character is a
number or a letter.

Bob

On Nov 16, 7:57am, Bob T. [email protected] wrote:

having them I have had no problems assembling the new string.
“Test Part 12 or 3 G 477”.gsub( /\D/, “” )
==>“123477”