Printing versus Using Puts in Ruby - dummies

Printing versus Using Puts in Ruby

By Christopher Haupt

When you’re using Interactive Ruby (IRB), you probably use Ruby’s built-in puts method, which prints a string for you. You also can use puts and another built-in output oriented method called print to print out a message and then gather some input from your user.

The print method is exactly like puts, but instead of automatically adding a newline character at the end of the string, print leaves the cursor on the same line at the end of the string.

A newline character (sometimes called a carriage return, line feed, or line separator) is an invisible character that instructs the terminal to move the current position at which it’s displaying characters down one line and all the way back to the left (by default). Newline, carriage return, and line feed are actually three different things, but you can just use the term newline.

The cursor in the terminal is the current position at which the terminal is printing out characters or waiting for you to type. In your terminal program, the cursor’s position is usually drawn as an underscore or block character. It may be blinking, too.

Follow these steps to start a program (in this example, the programs is one that enables you to draw shapes):

  1. Switch to your Atom editor and make sure that you’re looking at your new project window. It should be blank.

  2. Enter a comment at the top of the file as a reminder of what the program is going to do:

    # Ruby For Kids Project 4: Shapes
    # Programmed By: Chris Haupt
    # Experiment with drawing ASCII art shapes using code.

    Comments are labels, descriptions, explanations, or notes you put in your code to be read by you and other humans. Ruby doesn’t try to interpret or run comments. You let Ruby know that a line is a comment by adding the hash character (#) before your comment starts. Sometimes it’s useful to “comment out” code that isn’t working or that you don’t need but also don’t want to delete from the file. You simply put a comment character in front of the lines you want to hide from Ruby.

  3. Display a message to your user that will show up when the program is run:

puts "Welcome to Shapes"
print "How big do you want your shape? "