How to display a variable inside a string with Ruby

So, I have the following code that reads a text file line by line. Each line ends with a return carriage. Below is the code:

define host {
    use             servers
    host_name         ["buffy"]
    alias         ["buffy"]
    address       ["buffy"].mydomain.com
}

How to get rid of brackets 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
+5
source share
3 answers

you can use

#{data[0]}

instead of # {data}

This is because split creates an array of strings.

However, if you really want to just get the line without the end of the line end, you can use the strip method.

+5
source
#{data[0]}

split returns an array.

0
source

If your file is next

server1
server2

And you want to create a file like this:

define host {
use             servers
host_name       server1
alias           server1
address         server1.mydomain.com
}

define host {
use             servers
host_name       server2
alias           server2
address         server2.mydomain.com
}

I would do something like:

output = File.open("output", "w")

File.open("hosts").each_line do |line|
   server_name = line.strip
   text = <<EOF
define host {
use servers
host_name #{server_name}
alias #{server_name}
address #{server_name}.mydomain.com
}
EOF
    output << text
end

output.close
0
source

All Articles