How to Get Input with Gets in Ruby - dummies

How to Get Input with Gets in Ruby

By Christopher Haupt

Ruby provides a number of ways to get input from the user. You’ll use gets in this example. The gets method is basically the opposite of puts — instead of printing stuff, it gathers what the user types for you.

Programmers call setting a variable to a single value that can’t be changed hard coding. Hard-coded variables are sometimes necessary, but they aren’t flexible. It’s better when you can get input from your user to make the value dynamic (changeable on-the-fly) instead.

  1. Right after your print statement, collect the user’s input into a variable (shape_size):

    # Ruby For Kids Project 4: Shapes
    # Programmed By: Chris Haupt
    # Experiment with drawing ASCII art shapes using code.
    puts "Welcome to Shapes"
    print "How big do you want your shape? "
    print "How big do you want your shape? "
    shape_size = gets
  2. While you’re here, gather some other input from the user that will be used to change the way the ASCII shape is drawn with different patterns:

    print "Outside letter: "
    outside_letter = gets
    print "Inside letter: "
    inside_letter = gets
  3. Add some final lines to repeat back what the user entered before you start working on drawing the shape:

puts "About to draw a shape #{shape_size} big"
puts "using #{outside_letter} for the edge"
puts "and #{inside_letter} for the inside"