In this section we will learn what the puts() method is and how to use it in Ruby
Note: we’re assuming you’re familiar with variables in Ruby.
What is puts method in Ruby?
The `puts` is a method that allows us to send data (values) to the output stream so that users can see them.
Note: in the Ruby methods section, we will learn more about methods, but in short, they are a block of code with a name. For example, the puts method represents a block of code. Now, whenever we call this name, that block of code will run and it will do a set of operations for us.
Ruby puts method syntax:
puts value1, value2, value_n
The `puts` method takes one or more input (AKA argument) and sends those to the output stream.
These input values could be a raw value (like integer numbers, floating numbers, string etc.) Or we can pass it variables which the method takes the values inside those variables and sends them to the output stream.
Notes:
- The values (AKA arguments) of the puts method could be of different types (like integer, float values, string etc.)
- If we passed more than one value to the puts method, then they should be separated using comma `,`
- We can put parentheses around the arguments of the puts method, but that is optional:
- puts( value1, value2, value_n)
- The puts method adds a newline character at the end of each argument it takes and so each argument appears in a newline when we call the method.
Example: putting data to the output stream using puts method
nickname = "Jack" first_name = "John" puts first_name, nickname, 50, true puts "***" puts(false, 40, nickname)
Output:
John Jack 50 true *** false 40 Jack
How does puts method work in Ruby?
In the example above, we’ve called the puts method in three different statements:
The first statement was:
puts first_name, nickname, 50, true
Here the method is taking 4 arguments:
- The value of the first_name variable
- The value of the nickname variable
- The value 50
- And the value true (which is a boolean value)
So here the puts method sends each value to the output stream and as you can see, each value appeared on a newline.
Note: we’ve put a comma between each argument.
The second statement was:
puts "***"
This time, the method takes only one value, and that is a string with three asterisk characters.
The third statement was:
puts(false, 40, nickname)
As mentioned before, the use of parentheses is optional when using a method. So here, for the sake of demonstration, we’ve called the puts method and this time used the parentheses around the arguments we’ve passed to the method.