Lior
Lior

Reputation: 146

Reading string by string in a line - Ruby

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

Upvotes: 3

Views: 94

Answers (2)

akuhn
akuhn

Reputation: 27813

Use the CSV class if these are tab separated entries. CSV stands for "comma separated values" but the you can provide your own separator

require 'csv'

CSV.foreach("fname", :row_sep => "\t") do |row|
  # use row here...
end

See https://ruby-doc.org/stdlib-2.0.0/libdoc/csv/rdoc/CSV.html

Upvotes: 2

tadman
tadman

Reputation: 211740

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

Upvotes: 4

Related Questions