So I have the following code that reads a text file line by line. Each line ends with a return carriage. The code below outputs the following:
define host {
use servers
host_name ["buffy"]
alias ["buffy"]
address ["buffy"].mydomain.com
}
How do i get rid of the bracket and quotes?
File.open('hosts','r') do |f1|
while line = f1.gets
data = line.chomp.split("\n")
File.open("nagios_hosts.cfg", "a") do |f|
f.puts "define host {\n";
f.puts "\tuse servers\n"
f.puts "\thost_name #{data}"
f.puts "\talias #{data}"
f.puts "\taddress #{data}.mydomain.com"
f.puts "\t}\n\n"
end
end
end
Ruby Class Variables Class variables begin with @@ and must be initialized before they can be used in method definitions. Referencing an uninitialized class variable produces an error. Class variables are shared among descendants of the class or module in which the class variables are defined.
A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas.
String Interpolation, it is all about combining strings together, but not by using the + operator. String Interpolation works only when we use double quotes (“”) for the string formation. String Interpolation provides an easy way to process String literals.
You could Use
#{data[0]}
instead of #{data}
That's because split creates an array of strings.
However, if you really want to simply get the line without the trailing end of line, you can use the strip method.
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