Thuta Learning
BasicProgrammingbeginner

User Input (gets)

Relax. We'll talk through this in plain words — no textbook voice.

In terminal apps, gets is used to get data from the user. gets captures what the user types until they hit Enter. Since a newline gets tacked on at the end, it's common to strip it off with .chomp.

ruby
print "What's your name? "
name = gets.chomp

print "How old are you? "
age = gets.chomp.to_i

puts "Hello, #{name}. Next year you will be #{age + 1}."

print shows the prompt without moving to a new line. gets.chomp grabs the input text and removes the trailing newline from Enter. to_i converts the string to an integer.

You should see
What's your name? Aung How old are you? 20 Hello, Aung. Next year you will be 21.

Info

User input is a String by default. If you want to treat it as a number, you'll need to convert it with to_i or to_f.

Easy traps

  • If you just do age = gets.chomp and then try to compute age + 1, you can get a TypeError from adding a String and an Integer together.
User Input (gets) | Thuta Learning