user3007294 user3007294 - 1 year ago 92
Bash Question

Writing File with ARGV Ruby

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

teddy bear,$5.00

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'


input = ARGV.first'./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?


Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download