Reputation: 427
results = open('names.txt').map { |line| line.split(' ')[0]}
p results
n = "Names_In_Array.txt"
outfile = File.new(n, 'w')
outfile.puts(results)
outfile.close
I'm trying to add quote marks and a comma after each name so I have an array format (besides the brackets). At it's current state, it saves it back into a plain string.
Upvotes: 1
Views: 1704
Reputation: 880
It sounds like you want to a take a file like:
ben john joe adam mike bob
and serialize that into an object structure for reading later.
If that is the case, I'd recommend you have a look at YAML. It's built into Ruby and makes reading and writing data structures easy. For example:
require 'yaml'
names = File.read('names.txt').split(' ')
File.open('Names_In_Array.txt') {|f| f << YAML::dump(names)}
You're resulting file can be read in a subsequent program with
names = YAML::load(File.open('Names_In_Array.txt'))
Upvotes: 1
Reputation: 21791
If understood you correctly:
outfile.puts(results.map{ |m| "\'#{m}\'" }.join(', '))
Upvotes: 0