Search code examples
rubylinenewlinefile-readchomp

How to remove line break when reading files in Ruby


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.


Solution

  • 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}."