Why does '\n' not work, and what does $/ mean?
Why doesn't this code work:
"hello \nworld".eac开发者_开发知识库h_line(separator = '\n') {|s| p s}
while this works?
"hello \nworld".each_line(separator = $/) {|s| p s}
A 10 second google yielded this:
$/ is the input record separator, newline by default.
The first one doesn't work because you used single quotes. Backslash escape sequences are ignored in single quoted strings. Use double quotes instead:
"hello \nworld".each_line(separator = "\n") {|s| p s}
First, newline is the default. All you need is
"hello \nworld".each_line {|s| p s}
Secondly, single quotes behave differently than double quotes. '\n'
means a literal backslash followed by the letter n, whereas "\n"
means the newline character.
Last, the special variable $/ is the record separator which is "\n" by default, which is why you don't need to specify the separator in the above example.
Simple gsub!
your string with valid "\n"
new line character:
text = 'hello \nworld'
text.gsub!('\n', "\n")
After that \n
character will act like newline character.
精彩评论