Ruby User Input

THE-Spellchecker's avatar
Published Jul 29, 2021Updated May 15, 2024
Contribute to Docs

In Ruby, user input is made possible by the #gets method. During the executing of a Ruby program, when a line with the #gets method is read, the terminal is primed for input from the user. The input is returned as a string type after the #gets method is finished.

name = gets
puts "My name is #{name}!"

The output would be:

Melanie
My name is Melanie
!

If just the #gets method is used, the keystroke on the Enter key is submitted with rest of the input, hence why the ! is on a new line. This can be avoided with the #chomp method:

name = gets.chomp
puts "My name is #{name}!"

The output would be:

Brandon
My name is Brandon!
  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours

All contributors

Contribute to Docs

Learn Ruby on Codecademy

  • Front-end engineers work closely with designers to make websites beautiful, functional, and fast.
    • Includes 34 Courses
    • With Professional Certification
    • Beginner Friendly.
      115 hours
  • Learn to program in Ruby, a flexible and beginner-friendly language used to create sites like Codecademy.
    • Beginner Friendly.
      9 hours