Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to Get User Input in Ruby?

In this blog post, we will learn how to get user input in Ruby. Whether you are building a command line application or a simple script to automate a task, getting input from the user is often necessary. Ruby makes it easy to get input from the user in a simple way, and in this tutorial, we will cover different ways to do that.

Table of Contents

  1. Basic User Input in Ruby
  2. Chomp Method Explained
  3. Different Ways to Get User Input
  4. Prompting User for Input
  5. Validating User Input
  6. Conclusion

1. Basic User Input in Ruby

Getting user input in Ruby is as simple as using the gets method. The gets method reads a line of text from the standard input or, in simple terms, from the user's keyboard. Let's look at a simple example:

puts "What's your name?"
name = gets
puts "Hi #{name}!"

In this example, we first print a message to the console asking the user for their name. Then we use the gets method to get the user's input and store it in the variable name. Finally, we print a greeting message that includes the user's input.

However, if you run this code, you might notice that the output has an extra line break. This is because the gets method also captures the newline character \n when the user presses the Enter key. To remove this newline character, we can use the chomp method.

2. Chomp Method Explained

The chomp method is used to remove the newline character from the end of a string. This is especially useful when getting input from the user, as it helps to clean up the input and avoid any unexpected formatting issues. Here's the previous example, modified to use the chomp method:

puts "What's your name?"
name = gets.chomp
puts "Hi #{name}!"

Now, when you run this code, the output will be formatted correctly without any extra line breaks. It's a good practice to use chomp when getting user input to ensure that your code works as expected.

3. Different Ways to Get User Input

While gets is the most common way to get user input in Ruby, there are other methods available as well. Here, we will explore some of these alternatives.

3.1. ARGF

ARGF is a special object in Ruby that represents a virtual concatenation of files passed as command-line arguments. If no files are passed, ARGF will read from the standard input, just like gets. Here's an example of using ARGF to get user input:

puts "Enter a number:"
number = ARGF.gets.chomp
puts "You entered #{number}."

This code will work similarly to the previous examples, but it can also handle input from files if they are passed as command-line arguments.

3.2. STDIN

STDIN is another way to get input from the user. It is a global constant in Ruby that represents the standard input stream. You can use the gets method with STDIN to receive user input:

puts "Enter your favorite color:"
color = STDIN.gets.chomp
puts "Your favorite color is #{color}."

This code will work the same as the previous examples. While STDIN is not as commonly used as gets, it can be helpful in certain situations where you need to explicitly specify the input stream.

4. Prompting User for Input

In the previous examples, we used the puts method to print a message to the console before getting input from the user. This is a simple way to prompt the user for input, but there are other approaches that can make your code more readable and user-friendly.

4.1. Using print Instead of puts

The print method is similar to puts, but it does not add a newline character at the end of the output. This means that the user's input will appear on the same line as the prompt, making it easier to read:

print "Enter your age: "
age = gets.chomp
puts "You are #{age} years old."

In this example, the user's input will appear directly after the "Enter your age: " prompt, making it easy to see the connection between the two.

4.2. Using a Custom Prompt with gets

You can also pass a custom prompt directly to the gets method as an argument. This makes your code more concise and easier to read:

age = gets("Enter your age: ").chomp
puts "You are #{age} years old."

In this example, the custom prompt is passed directly to the gets method, and the user's input is captured and processed in the same line of code.

5. Validating User Input

When getting input from the user, it's essential to validate the input to ensure that it meets the requirements of your program. Here, we will discuss a few common ways to validate user input in Ruby.

5.1. Using Regular Expressions

Regular expressions are a powerful tool for validating user input. They allow you to define patterns that the input must match in order to be considered valid. Let's look at an example:

print "Enter your email address: "
email = gets.chomp

if email =~ /\A[\w+\-.]+@[a-z\d\-]+(\.[a-z]+)*\.[a-z]+\z/i
  puts "Your email address is #{email}."
else
  puts "Invalid email address."
end

In this example, we use a regular expression to validate that the user's input is a valid email address. The =~ operator checks if the input matches the regular expression, and if it does, the code prints a confirmation message. If the input does not match the regular expression, the code prints an error message.

5.2. Using Custom Validation Methods

You can also create custom validation methods to check user input against specific criteria. Let's look at an example that validates a user's age:

def valid_age?(age)
  age.to_i > 0 && age.to_i < 120
end

print "Enter your age: "
age = gets.chomp

if valid_age?(age)
  puts "You are #{age} years old."
else
  puts "Invalid age."
end

In this example, we define a custom method called valid_age? that checks if the user's input is a valid age. The method returns true if the input is a number between 1 and 119, and false otherwise. We then use this method to validate the user's input and print an appropriate message.

6. Conclusion

In this tutorial, we covered different ways to get user input in Ruby. We saw how to use the gets, ARGF, and STDIN methods to receive input, and how to use the chomp method to remove newline characters from the input. We also discussed various techniques for prompting the user for input and validating their input using regular expressions and custom validation methods.

By understanding these concepts and techniques, you will be better equipped to build user-friendly and robust Ruby applications that can interact with users and handle their input effectively. Happy coding!