1. Computing

Running Ruby Scripts

By

Running Ruby Scripts

Now that you know how to navigate to your Ruby scripts (or your rb files), it's time to run them. Open your text editor and save the following program as test.rb.

#!/usr/bin/env ruby

print "What is your name? "
name = gets.chomp
puts "Hello #{name}!"

Open a command line window and navigate to your Ruby scripts directory using the cd command. Once there, you can list files, using the dir command on Windows or the ls command on Linux or OS X. Your Ruby files will all have the .rb file extension. To run the test.rb Ruby script, run the command ruby test.rb. The script should ask you for your name and greet you.

Alternatively, you can configure your script to run without using the Ruby command. On Windows, the one-click installer already set up a file association with the .rb file extension. Simply running the command test.rb will run the script. In Linux and OS X for scripts to run automatically two things must be in place: a "shebang" line and the file being marked as executable.

The shebang line is already done for you; it's the first line in the script starting with #!. This tells the shell what type of file this is. In this case it's a Ruby file to be executed with the Ruby interpreter. To mark the file as executable, run the command chmod +x test.rb. This will set a file permission bit indicating that the file is a program and that it can be run. Now, to run the program simply enter the command ./test.rb.

Whether you invoke the Ruby interpreter manually with the Ruby command or run the Ruby script directly is up to you. Functionally, they are the same thing. Use whichever method you feel most comfortable with.

Continue to Using Pipe Characters.

  1. About.com
  2. Computing
  3. Ruby
  4. Beginning Ruby
  5. Running Ruby Scripts--Executing rb Files

©2014 About.com. All rights reserved.