How To Log To Console Ruby

As a Ruby developer, you must have come across situations when you need to log something to the console. Logging to console in Ruby is very easy and straightforward. In this blog post, we will learn various methods to log messages to the console in Ruby.

1. Using puts Method

The most common and widely used method to log to console in Ruby is the puts method. The puts method writes the given object(s) to the console followed by a newline.

puts "Hello, World!"

This will output:

Hello, World!

2. Using print Method

Another method that can be used to log to console in Ruby is the print method. The print method is similar to the puts method, but it does not append a newline at the end.

print "Hello, World!"

This will output:

Hello, World!

3. Using p Method

The p method is another way to log to console in Ruby. It is a combination of the puts and inspect method. The p method is very useful when you want to print the value and inspect the object at the same time.

array = [1, 2, 3]
p array

This will output:

[1, 2, 3]

The p method is especially helpful when logging objects that are not strings, as it uses the inspect method to return a human-readable representation of the object.

4. Using logger Library

Ruby also provides a built-in Logger class that allows you to log messages with different severity levels, such as DEBUG, INFO, WARN, ERROR, and FATAL. The Logger class is part of the standard library and can be easily used in your Ruby programs.

To use the Logger class, you need to require the ‘logger’ library and create a new instance of the Logger class, specifying the output destination for the log messages.

require 'logger'

logger = Logger.new(STDOUT)

logger.debug("This is a debug message.")
logger.info("This is an info message.")
logger.warn("This is a warning message.")
logger.error("This is an error message.")
logger.fatal("This is a fatal message.")

Conclusion

Logging to console in Ruby is very simple and can be done using various methods like puts, print, p, and the Logger class. Each method has its own use case, and you can choose the one that best fits your needs. Happy coding!