tags:

views:

36

answers:

4

Basic question.

Instead of adding '\n' between the elements:

>> puts "#{[1, 2, 3].join('\n')}"
1\n2\n3

I need to actually add the line feed character, so the output I expect when printing it would be:

1

2

3

What's the best way to do that in Ruby?

A: 

Ruby doesn't interpret escape sequences in single-quoted strings.

You want to use double-quotes:

puts "#{[1, 2, 3].join(\"\n\")}"

NB: My syntax might be bad - I'm not a Ruby programmer.

Anon.
+1  A: 

Escaped characters can only be used in double quoted strings:

puts "#{[1, 2, 3].join("\n")}"

But since all you output is this one statement, I wouldn't quote the join statement:

puts [1, 2, 3].join("\n")
Doug Neiner
+3  A: 

You need to use double quotes.

puts "#{[1, 2, 3].join("\n")}"

Note that you don't have to escape the double quotes because they're within the {} of a substitution, and thus will not be treated as delimiters for the outer string.

However, you also don't even need the #{} wrapper if that's all your doing - the following will work fine:

puts [1,2,3].join("\n")
Amber
@Dav, before I saw you answer I tested mine... and realized this. I guess I never tried it before, I only use substitution for simple variables or `variable.method` syntax. Great answer!
Doug Neiner
+1  A: 

Note that join only adds line feeds between the lines. It will not add a line-feed to the end of the last line. If you need every line to end with a line-feed, then:

#!/usr/bin/ruby1.8

lines = %w(one two three)
s = lines.collect do |line|
  line + "\n"
end.join
p s        # => "one\ntwo\nthree\n"
print s    # => one
           # => two
           # => three
Wayne Conrad
Or [1, 2, 3].join("\n")+"\n" :)
Veger
Indeed. One is terser, one does not duplicate the "\n". Which is preferred may be a good barometer of how a developer measures the "R" in "DRY".
Wayne Conrad