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
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.
Press Ctrl+H as a shortcut to find and replace a string in the current file.
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.
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") .
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
Or you can make it a one liner
File.write("hello.txt",File.open("hello.txt",&:read).gsub("install","latest"))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With