DEV Community

Monica
Monica

Posted on

1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

Best practices for optimal infrastructure performance with Magento

Running a Magento store? Struggling with performance bottlenecks? Join us and get actionable insights and real-world strategies to keep your store fast and reliable.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️