This Season
 

How to Write a Simple Program in Ruby

How to Write a Simple Program in Rubythumbnail
The open-source programming language Ruby, commended for its jewel-like clarity, is named after a precious stone.

Ruby is an extremely powerful object-oriented scripting language that is easy for anyone who understands the fundamentals of programming to learn. With powerful capabilities and an efficient syntax, the language has gained in popularity since its 1995 release. With a Ruby interpreter installed, you can create and run a very simple "first" program with Ruby that takes user input and prints output to the screen.

Related Searches:
    Difficulty:
    Moderately Easy

    Instructions

    Things You'll Need

    • Ruby interpreter installed
      • 1

        Open up any text editor to type your program into. For example, you can use Notepad, SciTE, jEdit or even the code view of Dreamweaver.

      • 2

        Create a new file and save it as "myprogram.rb" or a similar name with the .rb extension.

      • 3

        Type the following lines of text.

        print "What is your name? "
        name = gets.chomp
        print "How old are you? "
        age = gets.chomp
        print "Where do you live? "
        location = gets.chomp

        print "Hello " + name + "! You are " + age + " years old and live in " + location

      • 4

        Notice that the "gets" function reads in user input from the keyboard into variables. The "chomp" method after the "gets" function clears off the newline character that is put into the data when the user presses "Enter" after typing text in response to the prompt. The "print" function outputs text on the monitor screen.

      • 5

        Save the file and press the Start button in the lower left-hand corner of the screen. Open up a command-line prompt by typing "command prompt" without the quotes into the text box that appears and pressing "Enter."

      • 6

        Change directory to the location where you saved your program and run the program by typing "ruby myprogram.rb"

    Tips & Warnings

    • If you do not "chomp" the string that the user types in, you will get a newline character at the end of the data. This means when it is printed out, the text will be broken on the screen into several lines.

    Related Searches

    References

    Resources

    • Photo Credit Jupiterimages/Photos.com/Getty Images

    Read Next:

    Comments

    You May Also Like

    Follow eHow

    Related Ads