Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute a Ruby script as executable file?

i want to execute my ruby script as executable file and also i should execute at /usr/bin/ directory. I know it is possible like this.

#!/usr/bin/ruby
puts "hello"

And

chmod +x hello

But I also want to require some ruby file.

For example if I add

require './other_ruby_script' 

into my codes and I move the Ruby executable file to /usr/bin/, it gives me error for:

cannot load such file 'other_ruby_script'

I want to execute the Ruby file at /usr/bin directory.

So maybe I should compile it? But I couldn't compile because i didn't understand when google searches "How to compile?".

How can i create executable ruby code as suitable format for my codes. (require './other_file'). And i don't have to execute like this ./hello my executable file. Just i should execute as hello

like image 265
deniz Avatar asked Feb 06 '13 08:02

deniz


People also ask

How do I make a ruby file executable?

You can make the script executable with the following command: chmod +x hello. rb . chmod is a shell command that allows us to change the permissions for a file. The +x specifies that the script should be executable.

Can ruby be compiled to EXE?

ocra. OCRA (One-Click Ruby Application) builds Windows executables from Ruby source code. The executable is a self-extracting, self-running executable that contains the Ruby interpreter, your source code and any additionally needed ruby libraries or DLL.


2 Answers

#!/usr/bin/env ruby
require_relative 'other_ruby_script'
puts "hello"
like image 152
Alexey Avatar answered Sep 25 '22 15:09

Alexey


I think you ask how to configure the right loadpath. First, in your script I would do a:

puts $:

This should print whether you are loading the right Ruby environment (might be a problem if you are using rbenv or rvm). For example I get:

/Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/site_ruby/1.9.1
/Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/site_ruby/1.9.1/x86_64-darwin11.3.0
/Users/pmu/.rbenv/versions/1.9.3-p194/lib/ruby/site_ruby

As long as your loadpath does not contain the directory with the script 'other_ruby_script' you will get this error:

LoadError: cannot load such file -- other_ruby_script

So, you should try to add the load path with:

$:.unshift "#{File.dirname(__FILE__)}/../some_path"

If you are not loading the Ruby environment in the first place, your line:

#!/usr/bin/ruby 

needs to be setup to load the environment from Rbenv or Rvm

like image 22
poseid Avatar answered Sep 26 '22 15:09

poseid