0
0
RubyHow-ToBeginner · 3 min read

How to Run Ruby Script from Command Line: Simple Steps

To run a Ruby script from the command line, use the ruby command followed by the script filename, like ruby script.rb. Make sure you are in the directory where the script is saved or provide the full path to the script file.
📐

Syntax

The basic syntax to run a Ruby script from the command line is:

  • ruby: This is the command to run the Ruby interpreter.
  • script.rb: This is the name of your Ruby script file.

You can also provide a full or relative path to the script if it is not in the current directory.

bash
ruby script.rb
💻

Example

This example shows a simple Ruby script that prints a greeting message. You will see how to run it from the command line.

ruby
# hello.rb
puts "Hello, world!"
Output
Hello, world!
⚠️

Common Pitfalls

Common mistakes when running Ruby scripts include:

  • Not being in the correct directory where the script is saved.
  • Forgetting to include the ruby command before the script name.
  • Using the wrong file extension or misspelling the script filename.

Always check your current directory with pwd (Linux/macOS) or cd (Windows) and list files with ls or dir.

bash
Wrong way:
ruby hello

Right way:
ruby hello.rb
📊

Quick Reference

Here is a quick cheat sheet for running Ruby scripts:

CommandDescription
ruby script.rbRun the Ruby script named script.rb
ruby /path/to/script.rbRun a Ruby script using full path
pwd or cdCheck current directory to find your script
ls or dirList files in the current directory

Key Takeaways

Use the command ruby script.rb to run your Ruby script from the command line.
Make sure you are in the directory where the script is saved or provide the full path to the script.
Check your script filename and extension carefully to avoid errors.
Use pwd or cd and ls or dir to navigate and find your script.
Always include the ruby command before the script name; just typing the filename won’t work.