0

I am trying to add a linebreak to a text object in rails.

Using rails 5.0 and postgres 9.4

some_text = "string sentence one"
some_text += #how do i add line break here
some_text = "string sentence two"

I've tried chr(10), '\n', \n, '/\n/' and /\n/

How would I add a line break to some_text?

tl;dr

Below is a loop that I am using in a controller to loop through attributes of an object and try to add a line break to it

@some_text ||= ""
object.attributes.each do |attr_name, attr_value|
    @some_text << attr_value.to_s + "\n"
end

When I display the @some_text object in a view, it has no line breaks. If I save the @some_text object into postgres, it still has no line breaks.

1 Answer 1

1

It's "\n" (with double quotes):

some_text = "string sentence one"
some_text << "\n"
some_text << "string sentence two"

If you want to output multiline string in irb or der Rails console use puts. Whereas p doesn't work, because it shows control characters instead.

It is worth noting that line break in HTML are usually not displayed in the rendered document. To translate new line characters in strings (\n) into visible HTML line breaks (<br>) there a several options:

  • Translating the string (string_with_linebreaks.gsub("\n", '<br>')),
  • use Rails' simple_format text helper or a markdown parser,
  • place the string into a <pre> block that usually (unless the default css is changed) will preserves both spaces and line breaks or
  • declare a css rule like white-space: pre-line on the surrounding HTML tag.
Sign up to request clarification or add additional context in comments.

9 Comments

You know I tried both in the console and a rails controller and it did not break the line. Rails console returns: => "string sentence one\nstring sentence two"
In postgres it gets stored that way as well, not with a line break
How do you print to the console? It should work with puts, but not with p. How did you test in the controller? HTML doesn't show line breaks per default.
@HoosierCoder That's how the string will look when displayed as an inspect version, that is all non-printable or control characters will show up as things like \n. This is an old convention that's been adopted by many systems, including Postgres. What you see in this string form versus what you get when you print it will differ slightly.
I updated my question with details on how I use it in rails. You are right, if I use the console, and use puts some_text it does work. So, how would I get it to display in a database or a view, like it does with puts
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.