attaboy182
attaboy182

Reputation: 2079

Replace a word in a file in Ruby

I am new to Ruby and I have been trying to replace a word in a file. The code for that is as follows:

File.open("hello.txt").each do |li|
  if (li["install"])
  li ["install"] = "latest"
  puts "the goal state set to install, changed to latest"
  end
end

While the message in puts gets printed once, the word does not change to "latest" in that line of that file. Could anyone please tell me what's wrong here? Thanks

Upvotes: 6

Views: 10718

Answers (3)

engineersmnky
engineersmnky

Reputation: 29308

Or you can make it a one liner

File.write("hello.txt",File.open("hello.txt",&:read).gsub("install","latest"))

Upvotes: 12

Alex
Alex

Reputation: 699

The problem with your code is that you're not writing the changed line to the file.

I would recommend this:

lines = IO.readlines("hello.txt")
for line in lines
    if line["install"]
        line["install"] = "latest"
    end
end
f = File.open("hello.txt", "w")
for line in lines
    f.puts(line)
end
f.close

In line 1, IO.readlines() returns an array containing all the lines in the file. The rest of the program is fundamentally the same until we get to line 6, where the file is opened. File mode "w" tells Ruby to overwrite the file, which is what we want here. In line 8, we use file.puts to write each of the lines back to the file, with modifications. We use puts instead of write because and all the newlines were clipped off by IO.readlines(), and puts appends newlines while write does not. Finally, line 10 closes the file.

Upvotes: 2

Ivan Zarea
Ivan Zarea

Reputation: 2174

You'll also need to write back to the file. File.open without any arguments opens the file for reading. You can try this:

# load the file as a string
data = File.read("hello.txt") 
# globally substitute "install" for "latest"
filtered_data = data.gsub("install", "latest") 
# open the file for writing
File.open("hello.txt", "w") do |f|
  f.write(filtered_data)
end

Upvotes: 20

Related Questions