Mellon
Mellon

Reputation: 38842

Newbie: text replacement in my case

In my Ruby on Rails app, I have a method in my helper which opened a file by:

content = File.open(myfile.txt)

The content of the file is like:

my.car , my.seat, my.age;
my.son , my.dog, my.chair;
...

So, I split the content by ";" like following:

content.split(';').each do |line|
      #Here, I want to replace the text from "my" to "her" on each line
end

How to replace each line's "my" to "her" in the content?

that's to update content to:

her.car , her.seat, her.age;
her.son , her.dog, her.chair;
...

-------------------------- update ---------------------------------

I would like to update the content of the opened file , not only replace the string when read the content from the ruby code.

Upvotes: 0

Views: 287

Answers (2)

gioele
gioele

Reputation: 10205

There is no way to modify the content of a file on the fly. Files can only be appended, they cannot be expanded, so you cannot replace my with her.

You can start from this basic code:

buf = ""

File.open('myfile.txt') do |file|
    file.readlines.each do |line|
        buf << line.gsub('my', "her")
    end
end

File.open('myfile.txt', 'w') do |file|
    file << buf
end

Upvotes: 2

Adam Spiers
Adam Spiers

Reputation: 17916

line.gsub!(/my/, "her")

Although you may want to get more specific with the regular expression, e.g.

line.gsub!(/\bmy\./, "her")

Upvotes: 2

Related Questions