Danny
Danny

Reputation: 5400

Outputting to file with comma causing new line in file in ruby

So I have a file that I am trying to write to after getting a username, password and role from the user to add to this file. Everything appears to work well, but when I open the file for writing and enter the puts command, it creates a new line after the password section. Here is a snippet of the code.

File.open("user.file", "a") do |file|
  file.puts "#{userName}=#{passwordEncoded},#{role},enabled"

And here is what I get in the file itself afterwards

danny=ieSV55Qc+eQOaYDRSha/AjzNTJE=
,ROLE,enabled

It might have something to do with the = at the end of the encoded password but I am not sure. The passwords always end in an equal size so maybe that causes issues? But I am not sure here.

Upvotes: 0

Views: 123

Answers (2)

denis.peplin
denis.peplin

Reputation: 9851

Add chomp call to passwordEncoded variable to remove newline:

File.open("user.file", "a") do |file|
  file.puts "#{userName}=#{passwordEncoded.chomp},#{role},enabled"

Upvotes: 2

user229044
user229044

Reputation: 239311

Your passwordEncoded variable ends in a newline. The actual contents of the variable will be

"ieSV55Qc+eQOaYDRSha/AjzNTJE=\n"

There is no problem with your code. It is behaving exactly as expected.

Upvotes: 4

Related Questions