Ruby provides several methods for accepting user input, allowing developers to create interactive programs. Understanding these input methods is crucial for building dynamic applications.
The most common way to receive input in Ruby is through the gets
method. It reads a line of input from the user, including the newline character at the end.
print "Enter your name: "
name = gets
puts "Hello, #{name}"
In this example, the program prompts the user for their name and then greets them. However, the greeting will include a newline character.
To remove the trailing newline, you can use the chomp
method:
print "Enter your name: "
name = gets.chomp
puts "Hello, #{name}!"
Now the greeting will appear on the same line as the name.
When your script accepts command-line arguments, it's better to use STDIN.gets
instead of just gets
. This ensures that input is read from the standard input stream.
print "Enter a number: "
number = STDIN.gets.chomp.to_i
puts "You entered: #{number}"
Ruby input is always received as a string. To work with other data types, you'll need to convert the input:
gets.chomp.to_i
gets.chomp.to_f
gets.chomp.downcase == 'true'
For multiple inputs, you can use a loop or read specific number of lines:
puts "Enter three numbers:"
numbers = 3.times.map { gets.chomp.to_i }
puts "You entered: #{numbers.join(', ')}"
To further enhance your Ruby programming skills, explore these related topics:
By mastering Ruby input methods, you'll be able to create more interactive and user-friendly programs. Practice with different input scenarios to become proficient in handling various types of user interactions.