Leo_M
(Leo M.)
30 January 2011 01:47
1
Hello!
I'm a complete newbie in Ruby's world!
I'm just messing around with codings in disparate arguments.
Here, I'm trying to do a program which takes the text in a .txt file and
changes values by gsub! method!
The snag I'm encountering is when I have to make Ruby understand that it
has to consider the text inside a file!
file = File.open("/R/testo.txt", "r")
text = (file.each {|line| print line }).to_s
text.to_s
text.gsub!(/o/,"*")
That's what I've done, but it limits itself to print the text...!
How can I do?
Thanks a lot!
Cheers
···
--
Posted via http://www.ruby-forum.com/ .
The snag I'm encountering is when I have to make Ruby understand that it
has to consider the text inside a file!
file = File.open("/R/testo.txt", "r")
text = (file.each {|line| print line }).to_s
text.to_s
text.gsub!(/o/,"*")
That's what I've done, but it limits itself to print the text...!
How can I do?
text = File.read('/R/testo.txt')
text.gsub!(/o/, "*")
puts text
···
--
Anurag Priyam
http://about.me/yeban/
Leo_M
(Leo M.)
30 January 2011 10:24
3
Ohhhh I didn't know this method!
Thank you a lot
···
--
Posted via http://www.ruby-forum.com/ .
Leo M. wrote in post #978439:
file = File.open("/R/testo.txt", "r")
text = (file.each {|line| print line }).to_s
text.to_s
text.gsub!(/o/,"*")
Processing one line at a time is a good idea because it lets you handle
files bigger than will fit into memory.
This can be as simple as:
file = File.open("/R/testo.txt")
file.each { |line| print line.gsub!(/o/,"*") }
Or better, like this:
File.open("/R/testo.txt") do |file|
file.each { |line| print line.gsub!(/o/,"*") }
end
The second version will automatically close the file at the end of the
block.
I'd prefer "each_line" to "each". Not only is it clearer, but 'each' for
strings was removed from ruby 1.9 (although oddly not from files)
···
--
Posted via http://www.ruby-forum.com/\ .