There are 3 main ways we can use Ruby to print to the console. We can do this by using either the print, puts, or p commands. Let’s take a look at each one.
Let’s first look at printing to the console using the print command, with a very simple example.
some_string = "This is a string."
another_string = "This is another string."
print some_string
print another_string
#Output
This is a string.This is another string.
As you can see, the print command will print each string on the same line next to each other.
Let’s take a look at what the puts command will do.
some_string = "This is a string."
another_string = "This is another string."
puts some_string
puts another_string
#Output
This is a string.
This is another string.
As you can see, the puts command will return a newline after it prints, making it so each result is on its own line.
And finally, let’s take a look at what the p command will do.
some_string = "This is a string."
another_string = "This is another string."
p some_string
p another_string
#Output
"This is a string."
"This is another string."
The p command is similar to puts in that it will return a newline after it prints, making it so each result is on its own line. The p command is more for debugging your code, as it will help you know what value it is that is being printed. As in the p example above, you can see that we have a string object returned.
Let’s take a look at some more examples of each command in action.
some_string = "This is a string."
print some_string
puts some_string
p some_string
#Output
This is a string.This is a string.
"This is a string."
Let’s take a look at printing some numbers.
some_numbers = 123456
print some_numbers
puts some_numbers
p some_numbers
#Output
123456123456
123456
And printing an array of numbers.
some_array = [1,2,3,4,5,6]
print some_array
puts some_array
p some_array
#Output
[1, 2, 3, 4, 5, 6]1
2
3
4
5
6
[1, 2, 3, 4, 5, 6]
Here you can see how print and puts differ when printing an array.
Let’s try printing a Hash.
some_person = {"first_name" => "Peter", "last_name" => "Smith", "age" => "40"}
print some_person
puts some_person
p some_person
#Output
{"first_name"=>"Peter", "last_name"=>"Smith", "age"=>"40"}{"first_name"=>"Peter", "last_name"=>"Smith", "age"=>"40"}
{"first_name"=>"Peter", "last_name"=>"Smith", "age"=>"40"}
And finally, just printing a boolean value.
some_bool = true
print some_bool
puts some_bool
p some_bool
#Output
truetrue
true
Hopefully this article has been helpful for you to learn how to use Ruby to print to the console.