Prompts with Case and If Statements
So over the weekend, I had a random idea come to mind while waiting in the car for my brother. I wanted to input responses that would be given a response based on the input. It sounds simple enough, plus it’ll give me a chance to create something fun over the weekend. So let’s break this down. I’ll be discussing gets
methods and if
/ case
statements while providing examples. Below are examples for each option, but always feel free and test them on your irb
because, like one of my instructors always says, “Testing is free.”
gets
methods
So first things first. Let’s prompt our program to get the user input. There are three options for gets
methods, and they include gets
, gets.chomp
, and gets.strip
. Simply using gets
will return the input; however, as you see below, it’ll move everything after the string interpolation to a new line which can affect my conditional statements. This is happening because when you hit enter, it creates a new-line character known as /n
.
print "Hi, what's your name? "name = getsprint "Hi! Welcome #{name.capitalize}!"// Hi, what's your name? joy
// Hi! Welcome Joy
!
Demanding on your intentions, this may not be such a big deal, but if it is, then switching to gets.chomp
or gets.strip
would be more useful. When using gets.chomp
, you don’t have to worry about a newline but white space. gets.strip
however, it eliminates both the white space and newlines.
//gets.chomp methodprint "Hi, what's your name? "name = gets.chompprint "Hi! Welcome #{name.capitalize}!"// Hi, what's your name? joy
// Hi! Welcome Joy !
//gets.strip methodprint "Hi, what's your name? "name = gets.stripprint "Hi! Welcome #{name.capitalize}!"// Hi, what's your name? joy
// Hi! Welcome Joy!
if
/ case
statements
To add another layer of complexity to the situation, I want ruby to print back a specific response to the given input. This is were if
statements enter the picture. When used with operators like ==, !=, <=, >=, <, >, ||, &&
you can set up conditionals. These structures also use the following reserved words: if
, else
, elsif
, and end
.
print "Hi, what's your name? "name = gets.stripif name.downcase == "joy"print "Welcome back #{name.capitalize}! How's it going?"elseprint "Hi! Welcome #{name.capitalize}!"end
Sometimes if
statements may not always be the best option for your situation. Luckily for you case
Statements are another option to fall back on. There are three components to a case
statement: case
, when
, and else
. Personally, I prefer use case
statements because it helps your code become more readable and cleaner.
print "Hi, what's your name? "name = gets.stripcase namewhen "joy"print "Welcome Back! How's it going?"elseprint "Hi! Welcome #{name.capitalize}!"end
Feel free and comment, share and check out some of the resources posted below. Thanks for reading!