User Input

Back to Curriculum Index

Goals

  • Prompt a user to enter an input value and use that value in your program
  • Use developer skills to build an understanding of what unfamiliar code is doing

Getting User Input

Our programs haven’t been very exciting so far because we already know what will happen just by looking at the code. What if your program incorporated input from the user?

Directions:

  1. Read the code in this repl.it and guess what it will do. (It is also available below, if you prefer to preview it here)
  2. Run the program. It’s interactive, so be ready to type in your answers in the console area.

Takeaways

  • Instead of manually typing in every value, we can collect values from our user to provide a dynamic experience
  • When the code is being read, it will stop at gets.chomp and wait for the user to type input into the console
  • gets collects a string from the console, chomp removes the final character which is the enter/return


Try It: Getting User Input

Write a small program that asks a user theirs dogs name, then responds with a sentence of your choice! Consider: what variable name will you use to label that user input?

🌶 Finished Early? Click here for a challenge! 🌶

How could you modify this code so that the dogs name is capitalized correctly, no matter how they entered it?

Multiple User Inputs

We know how to get one input from a user. How do we go about getting multiple inputs?

Try It: Getting Multiple User Inputs

Write a program that asks a user for 3 questions. If you're not feeling creative, ask their name, city, and age. Output something like the following:

Your name is Amy and you live in Denver. Your are 100 years old.

Try running your program a few times with different values stored in the variables.

🌶 Option to try another Spicy Challenge 🌶

Modify the program so that when you ask the user the second question, you use their first input, etc.

Next: Arrays