๐ŸŽ“ A1Learner
๐Ÿ”

Ruby User Input

User input is text a person types while a program runs. The word gets reads one typed line into the program.

Reading a name

This program asks for a name and then greets it. The typed line for this run is Ana.

puts "What is your name?"
name = gets.chomp
puts "Hello, #{name}!"

Reading a number

This program asks for an age and adds 5 to it. The typed line for this run is 30.

puts "How old are you?"
age = gets.to_i
puts "In five years you will be #{age + 5}"

Example

puts "What is your name?"
name = gets.chomp
puts "How old are you?"
age = gets.to_i
puts "#{name} is #{age} years old"

Key points

  • gets reads one line of typed text.
  • A line from gets keeps its ending newline.
  • chomp gives the same text without the ending newline.
  • Text from gets is always a String.
  • to_i turns that text into a whole number.

In this example, the typed lines are Ana and then 30. The first gets line reads the name and chomp trims its newline. The second gets line reads the age and to_i turns the text into a number. The last line prints one sentence that uses both values.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz Ruby Compiler

Exercise

Why does the age from gets need to_i before the program adds 5?