Open In App

How to Get User Input in Ruby?

Last Updated : 10 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The input of users is a very vital part of many programs which allows customization and interaction. In Ruby, there are various methods to get input from the user, each having its own benefits and use cases. This article will discuss two different ways to obtain user input in Ruby.

Approach 1: Using the ‘gets’ Method

The gets method reads a line from standard input while chomp removes any trailing newline characters. It is simple and flexible allowing basic user input in many situations.

Syntax:

user_input = gets.chomp

Example:

Ruby
puts "Please enter your name:"
name = gets.chomp
puts "Hello, #{name}!"

OUTPUT:



ftfyguhi

OUTPUT


Approach 2: Utilizing STDIN.gets for Input Stream

While it shares similarities with gets, STDIN.gets tells us that it’s reading data from standard input as opposed to anything else even if the standard output has been redirected somewhere else. This is specifically useful when standard input may change or be redirected for whatever reason.

Syntax:

user_input = STDIN.gets.chomp

Example:

Ruby
puts "Please enter a number:"
number = STDIN.gets.chomp.to_i
puts "You entered: #{number}"

OUTPUT:


ftfyguhi

OUTPUT


CONCLUSION:

By mastering the different ways of acquiring inputs from users in Ruby, developers can design dynamic applications which are more interesting to use and interact with.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads