How to print keys and values from a text file

458 views Asked by At

I have a file called "output.txt":

    "name": "abc",
    "age": 28,
    "name": "xxx",
    "age": 11,
    "name": "yyyb",
    "age": 15,

I want to read the file and print the name and age values on one line, one after the other:

abc 28
xxx 11
yyyb 15

The code I wrote is:

  file_data = {}
   object= File.open('output.txt', 'r') do |file|
   file.each_line do |line|  
   key,value = line  
   file_data[value] = key
   puts file_data

I am getting:

{nil=>"    \"name\": \"abc"\",\n"}
{nil=>"    \"age\": 28,\n"}
{nil=>"    \"name\": \"11"\",\n"}
{nil=>"    \"age\": false,\n"}
{nil=>"    \"name\": \"yyyb\",\n"}
{nil=>"    \"age\": 15,\n"}
2

There are 2 answers

2
Maxim Pontyushenko On

The best way is to use some popular format like YAML or JSON so you can work with it using some library. Also you could achieve it with code like this:

file_data = ""
object= File.open('output.txt', 'r') do |file|
  file.each_line do |line|
    key, value = line.split(':').map{|e| e.strip.gsub(/(,|\")/,'')}
    file_data << (key == 'name' ? "#{value} " : "#{value}\n")
  end
end
puts file_data
2
Aleksei Matiushkin On
File.read('output.txt')
    .split(/\s*,\s*/)
    .each_slice(2)
    .each do |name, age|
  puts [name[/(?<=: ").*(?=")/], age[/(?<=: ).*/]].join ' '
end