How to remove line break when reading files in Ruby
consider also optional chomp parameter in File.readlines
File.readlines("/path/to/file", chomp: true)
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"
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}."