Splitting text string

I am working on a way to process the status of products and I want to
use a bar code reader to make things easier. I already have the scanner
which simply reads the bar code into the keyboard port and appends a
carriage return. I was thinking of printing bar codes that would
contain information which is useless externally but useful to my app.
For instance…

Bar code: 123456789
Which would break down into:

order (first three) => 123
product (next five) => 45678
status (last digit) => 9

I would then use a nested form to feed the information in the database.

My question is… I get the string from the barcode reader as one long
string of numbers with no delimiters so how do I break that string down?
I can make sure the position of the values is the same in the barcode
when we print them but split and chunk both want a delimiter. Thanks,

stephen

order (first three) => 123
stephen
Use ranges as an index:

~$ irb
irb(main):001:0> barcode = ‘123456789’
=> “123456789”
irb(main):002:0> order = barcode[0…2]
=> “123”
irb(main):003:0> product = barcode[3…7]
=> “45678”
irb(main):004:0> status = barcode[8…8]
=> “9”

-Jonathan N.

Jonathan N. wrote:

order (first three) => 123
stephen
irb(main):004:0> status = barcode[8…8]
=> “9”

-Jonathan N.

Another idea:

$ irb -r scanf

“123456789”.scanf("%3d%5d%1d")
=> [123, 45678, 9]

(note that the strings are converted to integers for you)

Joel VanderWerf wrote:

Jonathan N. wrote:

order (first three) => 123
stephen
irb(main):004:0> status = barcode[8…8]
=> “9”

-Jonathan N.

Another idea:

$ irb -r scanf

“123456789”.scanf("%3d%5d%1d")
=> [123, 45678, 9]

(note that the strings are converted to integers for you)

Another:

raise “Bad barcode” unless “123456789” =~ /\A(\d{3})(\d{5})(\d)\z/
order, product, status = $1, $2, $3

Joel VanderWerf wrote:

Another idea:

$ irb -r scanf

“123456789”.scanf("%3d%5d%1d")
=> [123, 45678, 9]

(note that the strings are converted to integers for you)

“123456789”.unpack(“A3A5A1”)
#=> [“123”, “45678”, “9”]

I don’t know how to use unpack to deliver integers. Strings may better
in this case anyway, because leading zero’s survive.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs