Friday, September 16, 2011

Read and Write normal text file using ruby

Hello rubies,
        Want to read or write the normal text file using ruby? There is inbuilt File library with ruby. lets we use that and generate simple .txt file and read that.
       
Write .txt file:

Lets we have dummy data:

dummy_data =  [[1,"Ruby on rails","50%"], [2, ".net", "70%"], [3, "java", "80%"]]
File.open("#{RAILS_ROOT}"+"/data.txt", 'w') do |file|
      # set header
         file << "S.No.\tTechnology\tTrend\n"
      # set data
         dummy_data.each do |d|
            file << "#{d[0]}\t#{d[1]}\t#{d[2]}\n"
         end 
end  

Now data.txt is generated in rails_root. lets we read content of .txt file.

file = File.new("#{RAILS_ROOT}/data.txt").read.to_a
data = file.reverse
# pop out the header first
header = data.pop.to_a
h_data = {}
header.each do |h|
  splited_header = h.split("\t")
  splited_header.collect{|h| h_data[h.strip] = []}
end

data.each do |d|
  content =  d.split("\t")
  h_data.keys.sort.each_with_index do |k, index|
    h_data[k] << content[index].strip
  end
end
puts "collected_data : " + h_data.inspect

# find highest trend
max_trend = h_data["Trend"].max
puts "#{h_data['Technology'][h_data['Trend'].index(max_trend)]} has highest(#{max_trend}) trend in IT Market."


This is the simplest way to reach our goal. hope this will help you out.

No comments:

Post a Comment