开发者

How to properly join LF character in an array?

开发者 https://www.devze.com 2022-12-16 03:28 出处:网络
Basic question. Instead of adding \'\\n\' between the elements: >> puts \"#{[1, 2, 3].join(\'\\n\')}\"

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?


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")


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")


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消