Misha1991 Misha1991 - 18 days ago 7
Ruby Question

Parsing and structuring of a text file

I need help and I use Ruby. I had a text file with next contain:

Head 1
a 10
b 14
c 15
d 16
e 17
f 88
Head 4
r 32
t 55
s 79
r 22
t 88
y 53
o 78
p 90
m 44
Head 53
y 22
b 33
Head 33
z 11
d 66
v 88
b 69
Head 32
n 88
m 89
b 88


And I want parse and structure this file to next plane. I want to get next data:

Head 1, f 88
Head 4, t 88
Head 33, v 88
Head 32, n 88
Head 32, b 88


Please tell me how how can I make such code on a ruby?

I think first I have its put all the lines in the array:

lines = Array.new
File.open('C:/file/file.txt', 'r').each { |line| lines << line }


but what should I do next?

Thanks!

Answer

If the answer to @mudasobwa question "Do you want to grab everything having 88 value?" this is the solution

lines = File.open("file.txt").to_a
lines.map!(&:chomp) # remove line breaks

current_head = ""
res = []

lines.each do |line|
  case line
  when /Head \d+/
    current_head = line
  when /\w{1} 88/
    res << "#{current_head}, #{line}"
  end
end

puts res
Comments