Running Ruby Scripts

How to actually create and run Ruby code from separate files on your command line.

Scroll down...

Content

Resources

Comments

In this lesson, we'll cover storing your methods in a separate .rb file and then running it on the command line.

Running a Script

You're probably tired of running your methods in IRB (if that's what you're still doing) so it's time to learn how to break them out into a separate script file which you can then run in its entirety from the command line.

It's easy -- just create a file with the extension .rb, navigate to that file's directory from the command line, and run it using $ ruby filename.rb (the dollar sign is just the command prompt). You'll be able to gets from and puts to the command line now!

# my_script.rb
def say_input
    puts "What should we say?"
    input = gets.strip
    puts "Okay, let's say: #{input}!"
end
say_input   # this is to actually run the method when the file loads

# the command line
$ ruby my_script.rb
What should we say?
say this!  # user types something like this
Okay, let's say: say this!!
#=> nil

For help, see this SO post

Shebangs to Save Effort

If you get tired of typing ruby in front of the file, you can tell your computer what to do instead. Just let it know that the file is executable and specify that Ruby should be used to run it. This takes 2 steps:

  1. Use the chmod command to declare the file executable. Just type $ chmod +x your_filename.rb once and you'll be able to execute it. This may not even be necessary depending on your current file permissions.
  2. Now you need to let the computer know that it should use the Ruby interpreter when running the file instead of any other options. That requires you to include, at the very top of the file (before any spaces or lines), a Shebang Line that points to your Ruby executable:
#!/usr/bin/ruby
code here

As long as you explicitly call the filepath (adding the ./ in front of it) of your script from the command line, your computer will know it's a Ruby file and it will run automatically:

# my_script.rb
#!/usr/bin/ruby
def say_input
    puts "What should we say?"
    input = gets.strip
    puts "Okay, let's say: #{input}!"
end
say_input
# From the command line:
$ ./my_script.rb
What should we say?
oop                     # User input
Okay, let's say: oop!
#=> nil

Requiring Scripts or Gems in IRB

If you want to include a gem file (a library of methods, for instance) or another Ruby script in your IRB session, use require. require will search for any gems you've downloaded from the internet. If you've explicitly provided a path to be required, for instance ./my_script.rb, it will bring in that specific file instead.

# IRB
> require './my_script'  # or specify './my_script.rb'
What should we say?

Once it's been required, you can run methods and access variables from that file in IRB.

# my_other_script.rb
def bambam
    puts "BAMBAMBAM!"
end

# IRB
> require './my_other_script.rb'
#=> true
> bambam
BAMBAMBAM!
#=> nil

Load vs Require

There's another method load which is almost identical to require but allows a file to be loaded multiple times.

> load `./my_script.rb`
#=> true
> load `./my_script.rb`
#=> true

This can be handy in IRB if you're developing a script and want to make changes to it before reloading again without having to completely quit out of IRB. require only allows you to load the file once and will not work if you try to do it again:

> require './my_script.rb'
#=> true
> require './my_script.rb'
#=> false
> load './my_script.rb'
#=> true
> require './my_script.rb'
#=> false
> load './my_script.rb'
#=> true

While load is handy when you're playing around with command line scripts because it saves you from quitting IRB to refresh your changes, you should stick with require if you use this functionality in your own scripts. That's because require makes sure you've only loaded the file once while, with load you might have accidental double-or-triple loads if multiple files require each other.

Accessing Inputted Variables

Another thing that you'll probably want to do at some point is to access the variables that were passed to your script from the command line. For instance, if you ran:

$ ruby ./string_printer_script "howdy" "everyone"

You've passed in "howdy" and "everyone". You access these inputs by digging into a special constant (which is a variable you shouldn't try to change) called ARGV. ARGV is simply an array that contains all your command line arguments:

# Filename: string_printer_script.rb
def string_printer_script    # No Ruby arguments...
    inputted_strings = ARGV  # But yes CLI arguments!
    puts "You inputted: "
    if ARGV.empty?
        puts "nothing :("
    else
        inputted_strings.each do |str|
          puts str
        end
    end
end

# CLI
$ ruby ./string_printer_script.rb "howdy" "everyone"
You inputted:
howdy
everyone

# IRB
> require './string_printer_script.rb'
#=> true
> string_printer_script
You inputted:
nothing :(
#=> nil
> string_printer_script "some" "cool" "stuff"
# ArgumentError: wrong number of arguments (1 for 0)
# Oops! Can't send in ARGV arguments from IRB...

As you can see in the last example above, you can only pass in command line arguments from the actual command line (not within IRB).

Other Special Constants

There are a few other special constants you can access from within your script:

  • __FILE__ is the name of the current file.
  • $0 is the main or original file that was run (which could be different from your script if your script had just been required by that original file).
  • $ (aka $LOAD_PATH) is an array that contains the "load path", or all the directories the interpreter searches through when it needs to find a file.

There is a trick you can sometimes use to check whether your script is being run from the command line or as part of a larger program instead. You might do so if you want to puts some stuff only if it's called from the CLI (to debug it maybe).

Just check whether $0 is the same as __FILE__:

# tell_me.rb
def tell_me
    if $0 == __FILE__
      puts "I'm a command line script now!"
    else
      puts "Someone else is running me (I feel so violated...)"
    end
end

# CLI
$ ruby ./tell_me.rb
I'm a command line script now!

# IRB
> load './tell_me.rb'
Someone else is running me (I feel so violated...)
#=> true

Your Text Editor Build: The Easy Way

Despite learning all those options, there's one which is particularly easy. Most modern text editors have the options to "build" or run your code right in the editor. The specifics of how to do so are just a Google search away for your particular editor.

For example, if you are using Sublime Text, you can run the currently open file simply by using the command CMD+B (Mac) to "build" the file. A little window will pop up at the bottom which displays the results as if you had typed $ ruby your_file.rb on the command line.

Code Review

The important bits of code from this lesson

# "Shebang" line to tell file to run as Ruby
# (optional) Uses the path to your Ruby executable
#!/usr/bin/ruby
# Run the file from the command line (no shebang)
$ ruby your_file.rb

# If using a "shebang" line atop the file
# Update permissions to allow execution (if using shebang)
$ chmod +x your_filename.rb
# Run file directly (without using Ruby explicitly)
$ your_file.rb


# Run the file using IRB
$ irb
> require './your_file.rb'
> load './your_file.rb'

Wrapping Up

There are a number of different ways to run your Ruby scripts and it's good to give each of them a try before you settle on one as your "go-to". A little bit of investment in learning these things can quickly add up to minutes and even hours of time.



Sign up to track your progress for free

There are ( ) additional resources for this lesson. Check them out!

Sorry, comments aren't active just yet!

Next Lesson: Test Yourself: Ruby Basics