Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 310
attaboy182 Avatar asked Mar 11 '14 20:03

attaboy182


People also ask

How to Find and replace in Rubymine?

Press Ctrl+Shift+R to open the Replace in Path dialog. In the top field, enter your search string. In the bottom field, enter your replacement string. Click one of the available Replace commands.

How do you search for a pattern and then replace it in an entire file?

Press Ctrl+H as a shortcut to find and replace a string in the current file.

How do you replace a section of a string in Ruby?

Changing a Section of a String Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.

How do you replace a word in Ruby?

First, you don't declare the type in Ruby, so you don't need the first string . To replace a word in string, you do: sentence. gsub(/match/, "replacement") .


3 Answers

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
like image 53
Ivan Zarea Avatar answered Oct 23 '22 13:10

Ivan Zarea


Or you can make it a one liner

File.write("hello.txt",File.open("hello.txt",&:read).gsub("install","latest"))
like image 41
engineersmnky Avatar answered Oct 23 '22 12:10

engineersmnky


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.

like image 21
Alex Avatar answered Oct 23 '22 12:10

Alex