DEV Community

Monica
Monica

Posted on

TIL about Ruby command line execution

This is a walk-with-me-while-I-do-things series, I'm going to tell you what I learned while I'm learning

You can execute a Ruby file by passing it on as an argument to the ruby. What if I told you you can require a library and give executable code directly to the command on the terminal?

The ruby command supports two options among others:
-r stands for require and receives as an argument the name of the Ruby file you want to load
-e stands for execute and receives as an argument a script

Let's have a file in the current directory called hello.rb that defines the Hello class like this:

class Hello
  def greet
    puts "Hello there!"
  end
end

By running

ruby -r "./hello" -e "h = Hello.new; h.greet"

the prompt will present you with the following output

Hello there!

You can even write a multiline script as if you were writing in a file

➜  first-repo git:(master) ✗ ruby -r "./hello" -e "
dquote> h = Hello.new
dquote> h.greet
dquote> "
Hello there!

Here is the documentation for all the options you can feed to the ruby command

Top comments (0)