How to Take Input from User in Ruby: Simple Guide
In Ruby, you can take input from the user using the
gets method, which reads a line from the standard input. To remove the trailing newline character, use chomp on the input string, like input = gets.chomp.Syntax
The basic syntax to take input from the user in Ruby is using the gets method. It reads a line from the keyboard as a string including the newline character at the end. To remove this newline, you use chomp.
gets: Reads input including newline.chomp: Removes the newline character from the input string.
ruby
input = gets.chomp
Example
This example asks the user for their name and then greets them. It shows how to use gets.chomp to get clean input without the newline.
ruby
puts "What is your name?" name = gets.chomp puts "Hello, #{name}!"
Output
What is your name?
Hello, Alice!
Common Pitfalls
A common mistake is to use gets without chomp, which leaves a newline character in the input string. This can cause unexpected behavior when printing or comparing strings.
Another pitfall is forgetting that gets always returns a string, so you need to convert it if you want a number.
ruby
puts "Enter your age:" age = gets puts "You are #{age} years old." # Includes newline # Correct way: age = gets.chomp.to_i puts "You are #{age} years old." # No newline, converted to integer
Output
Enter your age:
You are 25
You are 25 years old.
Quick Reference
Here is a quick summary of how to take input in Ruby:
| Method | Description | Example |
|---|---|---|
| gets | Reads a line from user input including newline | input = gets |
| chomp | Removes trailing newline from string | input = gets.chomp |
| to_i | Converts string input to integer | number = gets.chomp.to_i |
| to_f | Converts string input to float | number = gets.chomp.to_f |
Key Takeaways
Use
gets.chomp to read user input without the newline character.Remember
gets returns a string; convert it to number if needed with to_i or to_f.Always remove the newline to avoid unexpected output or logic errors.
Prompt the user clearly before calling
gets to improve user experience.