From: Joel VanderWerf Date: 2010-03-23T03:38:39+09:00 Subject: Re: splitting text string Jonathan Nielsen wrote: >> 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 > > 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 Nielsen > Another idea: $ irb -r scanf >> "123456789".scanf("%3d%5d%1d") => [123, 45678, 9] (note that the strings are converted to integers for you)