I have an input text file "input.txt" that looks like this:
Country Code ID QTY
FR B000X2D 75 130
FR B000X2E 75 150
How do I extract the first, second and the third string from each line?
This code maps a whole line into one field of array:
f = File.open("input.txt", "r")
line_array = []
f.each_line { |line| line_array << line }
f.close
puts line_array[1]
Which outputs:
FR B000X2D 75 130
Furthermore, how can I split one line into more lines based on a quantity number,
max(quantity) = 50 per line
so that the output is:
FR B000X2D 75 50
FR B000X2D 75 50
FR B000X2D 75 30
If this is space delimited, should be pretty easy to split things up:
File.readlines('input.txt').map do |line|
country, code, id, qty = line.chomp.split(/\s+/)
[ country, code, id.to_i, qty.to_i ]
end
You can also easily reject any rows you don't want, or select those you do, plus this helps with stripping off headers:
File.readlines('input.txt').reject do |line|
line.match(/\ACountry/i)
end.map do |line|
country, code, id, qty = line.chomp.split(/\s+/)
[ country, code, id.to_i, qty.to_i ]
end.select do |country, code, id, qty|
qty <= 50
end
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