Open In App

How to add new line in Ruby?

In Ruby, newlines (line breaks) play a crucial role in formatting and separating your code. Whether you're crafting clear error messages or building readable output, knowing how to add newlines is essential.

Here's a breakdown of various methods you can use:

1. The Almighty `puts`:

The built-in `puts` method is your go-to tool for printing data to the console, and it automatically adds a new line at the end by default. This makes it ideal for displaying simple messages:

puts "Hello, world!"  # Prints "Hello, world!" followed by a newline

2. String Interpolation with `\n`:

For more control over output formatting, you can use string interpolation within double-quoted strings (`"`). The `\n` escape sequence represents a newline character, allowing you to embed newlines within your strings:

name = "Alice"
message = "Welcome, #{name}\nHave a wonderful day!"

puts message  # Prints:
# Welcome, Alice
# Have a wonderful day!

3. The Multiline String Heredoc (`<<-HEREDOC`):

When you need to create multiline strings, especially for displaying formatted text, Ruby offers the heredoc syntax. It lets you define a string literal that spans multiple lines, preserving the line breaks:

prompt = <<-HEREDOC
What is your name?
>
HEREDOC

puts prompt  # Prints:
# What is your name?
# >

4. The Multiline String Slash (`/`) Syntax:

Similar to heredoc, the slash syntax (`/`) allows you to define a multiline string. However, it treats leading whitespace consistently across lines, which can be useful for code blocks within strings:

code_snippet = "/
  puts 'Hello from the multiline string!'
/"

puts code_snippet  # Prints:
# 
# puts 'Hello from the multiline string!'
# /

Choosing the Right Method:

Conclusion:

By mastering these techniques, you'll be able to effectively add newlines and manage your output in Ruby, creating clear, well-formatted, and user-friendly code.

Article Tags :