user3007294 user3007294 - 6 months ago 23
Bash Question

Writing File with ARGV Ruby

I am trying to get my output to look like this:

$100.00
teddy bear,$5.00
shirt,$22.75
pants,$50.35


However, when I run the command to write the input to the file, I get the wrong format:

ruby start.rb '$100.00\nteddy bear,$5.00\nshirt,$22.75\npants,$50.35'


start.rb:

input = ARGV.first
File.open('./data_files/list.txt', 'w') {|file| file.write(input)}


Final output (in my data_files/list.txt file):

$100.00\nteddy bear,$5.00\nshirt,$22.75\npants,$50.35


Any idea how to write the file so it appears in the correct format?

Thanks

Answer

The shell doesn't recognize \n as a newline in regular single-quoted strings; you are passing literal backslash-n to Ruby. (And Ruby doesn't process input strings the way it does literal strings in Ruby code.)

If your shell is bash, you can use $'...' ANSI strings instead:

ruby start.rb $'$100.00\nteddy bear,$5.00\nshirt,$22.75\npants,$50.35'

Otherwise, you can use literal newlines:

ruby start.rb '$100.00
teddy bear,$5.00
shirt,$22.75
pants,$50.35'