How to remove line break when reading files in Ruby

21.3k Views Asked by At

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.

6

There are 6 best solutions below

0
Myst On BEST ANSWER

Your code has a minor issue that causes the results you are experiencing.

when you use:

name1 = File.readlines('first.txt').sample(1)

The returned value ISN'T a String, but rather an Array with 1 random sample. i.e:

["Jhon"]

This is why you get the output ["Jhon"] when using print.

Since you expect (and prefer) a string, try this instead:

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

or:

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

or, probably what you meant, with no arguments, sample will return an object instead of an Array:

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

Also, while printing, it would be better if you created one string to include all the spaces and formatting you wanted. i.e.:

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

puts "#{name1} #{name2} #{name3}."
# or
print "#{name1} #{name2} #{name3}."
1
Khoga On

puts adds a newline at the end of the output. print does not. Use print. It may solve your issue. Also, use .strip.

"\tgoodbye\r\n".strip   #=> "goodbye"
12
Cary Swoveland On

If:

name1 = ["Josh\n"]
name2 = ["Bobby\n"]
name3 = ["Green\n"]

it's just:

puts [name1, name2, name3].map { |a| a.first.strip }.join('')
  #=> JoshBobbyGreen
1
sbs On
puts %w(first middle last).map { |e| IO.readlines("#{e}.txt").sample.strip }.join
0
Nick Roz On

So as to avoid redundant \n's I'd rather use split:

File.read('first.txt').split("\n") # double quotes are important!

So as to avoid getting array use sample method without arguments:

File.read('first.txt').split("\n").sample
0
M. Modugno On

consider also optional chomp parameter in File.readlines

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