I have a file named ama.txt and the content of the file is like this:
name age hobby sex
amit 45 music male
sumit 35 cricket female
Now I can open the file like this:
File.open("ama.txt").each do
end
How can I modify the hobby column of the file?
The general pattern for something like this is roughly as follows:
cols = line.split(/\s+/) and then you want to edit cols[2], though I don't know if the changes fit a pattern or what.Ruby, like most scripting languages, has a lot of built-in ways to make some of these steps go quicker, but that's the basic pattern. Dmitry is potentially right that a CSV reader would help you here, but I can't see how well-formatted (or not) your data is, so I'm not even going to get into that.
Finally, and not to be rude, but it doesn't seem that you know Ruby especially well. Why is Ruby a requirement? Do you know another scripting language? How well do you know Ruby? In general, people here will help you with things, but not simply write code for you.
To answer Amit's question about step 4: If you have a new file open for writing, you will have a filehandle - a variable in your program pointing to the open file. You can write to that file by using the filehandle as a receiver for puts. This looks weird at first, since puts looks like a function normally, but it is a method call in Ruby. Try this in irb or a short Ruby script:
fh = File.open('test.txt', 'w')
fh.puts "hello, world"
fh.close
Another short example:
#!/usr/bin/env ruby
out_file = File.open('output.txt', 'w')
File.open('input.txt', 'r').each do |line|
out_file.print line.sub('foo', 'bar')
end
out_file.close
# no need to close the input file since the block version closes it for us
# automagically
# Maybe better to put the whole thing in a double block, though you may
# find this harder to follow at first
File.open('output.txt', 'w') do |out_file|
File.open('input.txt', 'r').each do |line|
out_file.print line.sub('foo', 'bar')
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With