Search code examples
rubymergenewlineconcatenation

Ruby: strings concated with "\n" returned in one line


I have this code:

def rectangle
  "|------------------|\n" +
  "|                  |\n" +
  "|                  |\n" +
  "|                  |\n" +
  "|                  |\n" +
  "|                  |\n" +
  "|                  |\n" +
  "|                  |\n" +
  "|                  |\n" +
  "|------------------|\n"
  end

and I want to refactor it. But for some reason, if I try to concat/merge the strings in any other way "\n" stops working, and it's returned in one line.

def rectangle
    a = "|------------------|\n"
    b = "|                  |\n"
    a + b + a
end

I tried using

System.getProperty("line.separator", "\n")

as suggested in similar posts, but it's not helpful (or I'm not doing it right). It's part of my course. Feels like I'm missing something obvious.


Solution

  • A simple example is:

    def rectangle
      a = "|#{'-' * 10}|"
      b = "|#{' ' * 10}|"
      ([a] + [b] * 5 + [a]).join("\n")
    end
    
    puts rectangle