简体   繁体   中英

Reading and modifying lines in a file using Ruby

I'm just getting started with Ruby, and my first program reads from a txt file and prints a modified version of each line to another one. The idea is to get this:

- Book Title *Book Author*

To this:

  Book Title     Book Author

My code looks like this:

listold = File.open('listas.txt', 'r+')
listnew = File.new('lista.txt', 'w+')
listold.each_line {|line|
  nome, autor = line.split(' *')
  nome['- '] = '  '
  autor = autor.chomp('*')
  listnew.puts nome << "\t" << autor
}

The problem I'm having is it only works for the last line in a file. For the other ones, the \\t spacing is very small, and the last * doesn't get cut. Can anybody help me?

Your split matches a space followed by a *.

You may want to split on '*' instead of ' *'.

I tried your code, it works for every line of my test file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM