Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display a variable inside string with Ruby

Tags:

ruby

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
like image 958
sdot257 Avatar asked Dec 22 '09 17:12

sdot257


People also ask

How do I use a variable in Ruby?

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.

How do you find the part of a string in Ruby?

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.

How do you interpolate a string in Ruby?

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.


1 Answers

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.

like image 125
phtrivier Avatar answered Oct 03 '22 19:10

phtrivier