How to remove line break when reading files in Ruby

marriedjane875 picture marriedjane875 · Sep 27, 2015 · Viewed 15.5k times · Source

I'm trying to get rid of the brackets [] and the new line \n from being printed.

My code looks like:

name1 = File.readlines('first.txt').sample(1)
name2 = File.readlines('middle.txt').sample(1)
name3 = File.readlines('last.txt').sample(1)

name = print (name1.strip 
    print name2.strip 
    print name3.strip)

puts name

I would like the output to look like JoshBobbyGreen. However, it looks like:

[\"Josh\\n\"][\"Bobby\\n\"][\"Green\\n\"]

I've tried using .gsub, chomp and split but maybe I'm using them wrong.

Answer

M. Modugno picture M. Modugno · Mar 20, 2020

consider also optional chomp parameter in File.readlines

File.readlines("/path/to/file", chomp: true)