1

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"}
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
user1642224
  • 61
  • 14
  • Don't assign the line to two variables and put it in a hash and print that. Just parse it (probably with a regular expression) and print the parts you want. – Dave Schweisguth Apr 21 '16 at 15:31
  • Why aren't you using a yaml file? – 13aal Apr 21 '16 at 15:31
  • Yes, it's far better to use YAML or JSON because it makes outputting and parsing trivially simple. You shouldn't be hand coding formatting and parsing if it can be done for you. – Keith Bennett Apr 21 '16 at 15:38
  • @ Dave Schweisguth can you please give the example of the code . – user1642224 Apr 21 '16 at 15:38
  • Hi all i am using ruby 1.8.7 which is there on our servers --with using json it is giving an error cannot parse it. so trying on another way – user1642224 Apr 21 '16 at 15:48
  • _Sidenote_: storing an input in hash leads to the incomplete result because of duplicated keys. Do you want just to print input out, or you need to store it somehow? – Aleksei Matiushkin Apr 21 '16 at 15:51
  • @ mudasobwa i want to print it out – user1642224 Apr 21 '16 at 15:52
  • Welcome to Stack Overflow. This looks like an XY problem, where you're asking about Y but should ask about X, which would be "How can I store the data from a hash?" – the Tin Man Apr 21 '16 at 16:33

2 Answers2

0

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
Maxim Pontyushenko
  • 2,983
  • 2
  • 25
  • 36
0
File.read('output.txt')
    .split(/\s*,\s*/)
    .each_slice(2)
    .each do |name, age|
  puts [name[/(?<=: ").*(?=")/], age[/(?<=: ).*/]].join ' '
end
Aleksei Matiushkin
  • 119,336
  • 10
  • 100
  • 160