Ruby - Saving Data to CSV File

Introduction

The CSV module handles the writing action.

Demo

require 'csv' 


File.open("test.txt", "w") do |f| 
  f.puts "Java,Manager,Logic,45\n" 
  f.puts "Json,Data,Female,23\n" 
  f.puts "Database,DBA,Female,38\n" 
end #   w  ww  . java 2  s. co m

people = CSV.read('text.txt') 
laura = people.find { |person| person[0] =~ /Java/ } 
laura[0] = "Java 11" 

CSV.open('text.txt', 'w') do |csv| 
  people.each do |person| 
    csv << person 
  end 
end

Result

Here, you load in the data, find a person to change, change her name, and then open up the CSV file and rewrite the data back to it.

Related Topic