How to Replace Multiple Newlines in a Row with One Newline Using Ruby

How to replace multiple newlines in a row with one newline using Ruby

This works for me:

#!/usr/bin/ruby

$s = "foo\n\n\nbar\nbaz\n\n\nquux";

puts $s

$s.gsub!(/[\n]+/, "\n");

puts $s

How can I remove the string \n from within a Ruby string?

You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.

Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.

While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.

In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.

See here for more info

ruby gsub new line characters

If you have mixed consecutive line breaks that you want to replace with a single space, you may use the following regex solution:

s.gsub(/\R+/, ' ')

See the Ruby demo.

The \R matches any type of line break and + matches one or more occurrences of the quantified subpattern.

Note that in case you have to deal with an older version of Ruby, you will need to use the negated character class [\r\n] that matches either \r or \n:

.gsub(/[\r\n]+/, ' ')

or - add all possible linebreaks:

/gsub(/(?:\u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029])+/, ' ')

Ruby: replace a multi-line text inside a document with another text

Regular expressions, in ruby, disable multi-line mode matching by default. This means the wildcard . character does not match new-lines.

You can enable this with the /m modifier:

/@NiceFunction(.*)@End/m

This attempt you made also seems reasonable:

/@NiceFunction([.\n]*)@End/

...But unfortunately when inside a character set, . loses its special meaning - so this pattern is actually just looking for repeats of the two characters "." and "\n", and would not match anything else.

There is, however, a similar approach you could have taken to match "any character, including newline", without enabling multiline mode. You can do something like this:

/@NiceFunction([\s\S]*)@End/

...Which is saying to match "any whitespace, or non-whitespace". In other words, absolutely anything.

The above approach would technically work for any pairing of negated groups - e.g. [\d\D], or [\w\W], or [\h\H], ... but it's somewhat of an unofficial standard to use [\s\S] for this purpose.

Remove multiple spaces and new lines inside of String

check out Rails squish method:

https://api.rubyonrails.org/classes/String.html#method-i-squish

Breaking up long strings on multiple lines in Ruby without stripping newlines

Three years later, there is now a solution in Ruby 2.3: The squiggly heredoc.

class Subscription
def warning_message
<<~HEREDOC
Subscription expiring soon!
Your free trial will expire in #{days_until_expiration} days.
Please update your billing information.
HEREDOC
end
end

Blog post link: https://infinum.co/the-capsized-eight/articles/multiline-strings-ruby-2-3-0-the-squiggly-heredoc

The indentation of the least-indented line will be
removed from each line of the content.

Ruby backslash to continue string on a new line?

That is valid code.

The backslash is a line continuation. Your code has two quoted runs of text; the runs appear like two strings, but are really just one string because Ruby concatenates whitespace-separated runs.

Example of three quoted runs of text that are really just one string:

"a" "b" "c"
=> "abc"

Example of three quoted runs of text that are really just one string, using \ line continuations:

"a" \
"b" \
"c"
=> "abc"

Example of three strings, using + line continuations and also concatenations:

"a" +
"b" +
"c"
=> "abc"

Other line continuation details: "Ruby interprets semicolons and newline characters as the ending of a statement. However, if Ruby encounters operators, such as +, -, or backslash at the end of a line, they indicate the continuation of a statement." - Ruby Quick Guide

ruby .split('\n') not splitting on new line

You need .split("\n"). String interpolation is needed to properly interpret the new line, and double quotes are one way to do that.

How to do a newline in output

Use "\n" instead of '\n'



Related Topics



Leave a reply



Submit