Hi, I’m new to ruby, and am having trouble with the following (\n is
newline on a Mac).
e.g.
line = “foo bar”
line = line.sub(/ /, ‘\n’)
puts line
This produces:
foo\nbar
when what I want (and expected) was:
foo
bar
(This is just a toy example; I don’t actually want to split lines on
spaces.) What I don’t understand is how to insert a true newline into a
string so that it outputs as such.
In ruby “\n” is a newline, while ‘\n’ is backslash followed by an n.
Perfect. Thanks. I had tried that with my more complicated example
(which included reference to capture groups from the regex) and it
didn’t work, but now I realise I need to concatenate the pieces together
with a mix of single and double quotes to get it to work.
Perfect. Thanks. I had tried that with my more complicated example
(which included reference to capture groups from the regex) and it
didn’t work, but now I realise I need to concatenate the pieces together
with a mix of single and double quotes to get it to work.
Well you could also use double quotes exclusively and use \1, \2 etc.
to
refer to the captures.
It’s about Perl but the same principles hold in Ruby except there’s no
platform where “\n” == “\015”, and that the I/O layer is stdio instead
of PerIO (in MRI).