ruby script for reading the contents of a file and appending in othere file


Content of text file
readdata.txt

Hi, This is Pravin Mishra
Ruby on rails developer
From India

and generating some output based on the content:

readfile.rb


class ReadFile
 
  def execute
    file = File.open(“readdata.txt”)
    contents = []
    all_data = Hash.new
    file.each {|line|
        tokens = line.split(” “)
       
        if tokens.count > 1
            tokens.each_with_index do |data, index|
              all_data[index] = data
            end
            contents << all_data
            all_data = Hash.new
        end
        
        my_file = File.new(“new_file.txt”, “w”)
        my_file.puts contents
    }

  end
 
end

if __FILE__ == $0
  sql = ReadFile.new
  sql.execute
end

Run from the command line as:

> ruby readfile.rb

Out put would be
{0=>”Hi,”, 1=>”This”, 2=>”is”, 3=>”Pravin”, 4=>”Mishra”}
{0=>”Ruby”, 1=>”on”, 2=>”rails”, 3=>”developer”}
{0=>”From”, 1=>”India”}
in new_file.txt

that’s it…!!!

Advertisements

2 thoughts on “ruby script for reading the contents of a file and appending in othere file

  1. Normally I do not learn post on blogs, however I wish to say that this write-up very forced me to check out and do so! Your writing taste has been surprised me. Thank you, very nice article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s