eHow Blog:

User-Submitted Article

How to Get User Input in Ruby

Ruby is an extremely powerful programming/scripting language. With powerful capabilities and an efficient syntax, many things are possible with Ruby. This article explains how to read input from the user.

Difficulty: Easy
Instructions

Things You'll Need:

  • Ruby interpreter
  • Keyboard
  1. Step 1

    Open up any text editor, such as notepad, wordpad or SciTE. Ruby code can be edited using any editor that outputs plain text.

  2. Step 2

    Type in the following code:

    puts "What is your name?"
    name = gets.chomp

    puts "Hello " + name + "!"

  3. Step 3

    The "puts" function in ruby will print data to the screen, followed by the enter key or newline. This results in a prompt "What is your name?" for the user to answer. The "gets" function that we call immediately after reads data from the keyboard, and stores it in the variable "name". the ".chomp" will clear off the newline character created when the user pressed the enter key to type in data. We then print the stored data back out to the screen with a nice message.

  4. Step 4

    Save your file as "myprogram.rb" and then open up a command line prompt. Change directory (cd) to the location where you saved your file, and then type "ruby myprogram.rb" to watch your program run.

Tips & Warnings
  • If we do not 'chomp' the text returned by the gets function, then when we print the data back out it will have an annoying break in the flow of text. This is because it stores the "enter" key pressed by the user.
Subscribe

Post a Comment

Post a Comment

Related Ads

  • Have you done this? Click here to let us know.
I Did This
Tags

Computers Fans

Follow us

  • Computers
  • Computers
Get Free Computers Newsletters
eHow At Home
eHow At Home

Copyright © 1999-2010 eHow, Inc. Use of this web site constitutes acceptance of the eHow Terms of Use and Privacy Policy .   en-US † requires javascript

eHow Computers
eHow_eHow Technology and Electronics