Gsub! on a txt file

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

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

Ohhhh I didn’t know this method!

Thank you a lot :slight_smile:

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)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs