Ruby - Get User Input

1. Introduction

To make programs dynamic and user-driven, it's often necessary to take various kinds of inputs. In Ruby, the gets method is typically used to capture this input. However, the nature of the input (string, integer, float, etc.) requires us to handle it differently to use it correctly in our program. This guide will demonstrate how to capture various types of inputs from the user.

2. Program Steps

1. Open your Ruby environment or editor.

2. Use the puts method to ask the user for a specific type of input.

3. Capture the input using the gets method.

4. Convert the input to the desired type (if necessary).

5. Display the input.

3. Code Program

# Ask the user for a string input
puts "Enter your name:"
name = gets.chomp
puts "Hello, #{name}!"
# Ask the user for an integer input
puts "Enter your age:"
age = gets.chomp.to_i
puts "You are #{age} years old."
# Ask the user for a floating-point number
puts "Enter your height in meters:"
height = gets.chomp.to_f
puts "Your height is #{height} meters."
# Ask the user for a boolean (yes/no) input
puts "Are you a programmer? (yes/no)"
is_programmer = gets.chomp.downcase == 'yes' ? true : false
puts "Programmer status: #{is_programmer}"

Output:

Enter your name:
John
Hello, John!
Enter your age:
25
You are 25 years old.
Enter your height in meters:
1.75
Your height is 1.75 meters.
Are you a programmer? (yes/no)
yes
Programmer status: true

4. Step By Step Explanation

1. name = gets.chomp: This captures a string input. chomp is used to remove the newline that gets method adds it by default.

2. age = gets.chomp.to_i: The gets method returns a string by default. We chain the to_i method to convert the string to an integer.

3. height = gets.chomp.to_f: Similar to the above, but we use to_f to convert the string to a floating-point number.

4. For the boolean input, we check if the user's response is 'yes'. We use the ternary operator to assign true if the user's input is 'yes', and false otherwise. It's important to use downcase to make the comparison case-insensitive.


Comments