Ruby Q & A

 

What is the difference between ‘puts’ and ‘print’ in Ruby?

In Ruby, both the `puts` and `print` methods are used to display output to the console, but they have some key differences in how they format and handle the output:

 

  1. `puts` (Put String):

   – `puts` is primarily used for displaying output followed by a newline character (`\n`). This means that each time you use `puts`, the next output will appear on a new line.

   – It’s particularly useful when you want to format output in a way that separates lines, making it more readable.

   – `puts` automatically appends a newline character at the end of the output, so you don’t need to explicitly add it.

   – Example:

 ```ruby

   puts "Hello,"

   puts "World!"

   ```

 

   Output:

```

   Hello,

   World!

   ```

 

  1. `print`:

   – `print`, on the other hand, is used for displaying output without automatically adding a newline character. It prints the text exactly as it is, without any line breaks.

   – It’s useful when you want to display content on the same line or when you need precise control over the formatting of the output.

   – If you want to add a newline, you need to do so explicitly by including `”\n”` in the text you pass to `print`.

   – Example:

 ```ruby

   print "Hello, "

   print "World!"

   ```

 

   Output:

   ```

   Hello, World!

   ```

 

The main difference between `puts` and `print` in Ruby is how they handle line breaks. `puts` adds a newline character by default, while `print` does not. Your choice between them depends on the specific formatting requirements of your program. If you want each piece of output on a new line, use `puts`. If you want to display output on the same line or need precise control over line breaks, use `print`.

Previously at
Flag Argentina
Chile
time icon
GMT-3
Experienced software professional with a strong focus on Ruby. Over 10 years in software development, including B2B SaaS platforms and geolocation-based apps.