Horje
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:

Ruby
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:

Ruby
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:

Ruby
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:

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

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

Choosing the Right Method:

  • Use `puts` for simple output with automatic newlines.
  • Employ string interpolation with `\n` to insert newlines within strings for controlled formatting.
  • Opt for heredoc for multiline text displays where you want to preserve line breaks and indentation as written.
  • Choose the slash syntax for multiline strings where consistent leading whitespace management is desired, especially for code snippets embedded within strings.

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.




Reffered: https://www.geeksforgeeks.org


Ruby

Related
How to create table in Ruby on Rails? How to create table in Ruby on Rails?
How to create API in Ruby on Rails? How to create API in Ruby on Rails?
How to parse HTML in Ruby? How to parse HTML in Ruby?
How to Convert a String to Lower or Upper Case in Ruby? How to Convert a String to Lower or Upper Case in Ruby?
How to Return Multiple Values in Ruby? How to Return Multiple Values in Ruby?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13