24

In ruby heredoc:

a = <<~TEXT
  asd
  asd
TEXT

it will generate:

[21] pry(main)> a = <<~TEXT
[21] pry(main)*   asd
[21] pry(main)*   asd
[21] pry(main)* TEXT
=> "asd\n" + "asd\n"

It generate a \n at the end of string, how to avoid this?

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
Moon soon
  • 2,616
  • 2
  • 30
  • 51

2 Answers2

33

As sagarpandya82 points out, you will need an additional action (i.e. chomp) to remove that extra \n.

You can use chomp along with heredoc like this:

a = <<~TEXT.chomp
  asd
  asd
TEXT
#=> "asd\nasd"
Gerry
  • 10,337
  • 3
  • 31
  • 40
0
<<-TEXT.squish.squeeze(' ')
  aa
                  b
TEXT
# => "aa b"
Almokhtar
  • 135
  • 2
  • 10
  • 3
    While this code may solve the question, [including an explanation](https://meta.stackoverflow.com/q/392712/8289918) of how and why this solves the problem would really help to improve the quality of your post and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Lauren Yim Sep 13 '20 at 01:43