How can I execute a Ruby script as an executable?

I want to execute my ruby ​​script as an executable, and also execute in the / usr / bin / directory. I know this is possible.

#!/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 to / usr / bin /, it gives me an error for:

cannot load such file 'other_ruby_script'

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

So maybe I should compile it? But I could not compile, because I did not understand when Google search queries "How to compile?".

How can I create ruby ​​executable code as a suitable format for my codes. (requires "./other_file"). And I do not need to perform like that. / hello is my executable. I just have to perform as hello.

+4
source share
4 answers

I think you are asking how to configure the correct boot path . First, in your script, I would do:

 puts $: 

This should print if you are loading the correct Ruby environment (maybe a problem if you use 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 a directory with script 'other_ruby_script', you will get this error:

 LoadError: cannot load such file -- other_ruby_script 

So you should try to add the boot 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 

you must configure the boot environment from Rbenv or Rvm

+2
source
 #!/usr/bin/env ruby require_relative 'other_ruby_script' puts "hello" 
+2
source

You can write a shell script from which you will execute the ruby ​​file. You will need to export PATH and GEM_HOME to a shell script. The shell script will look like this:

 #!/bin/bash export PATH = /usr/local/rvm/gems/ruby-1.9.3-p194 export GEM_HOME = /usr/local/rvm/gems/ruby-1.9.3-p194 cd /path/to/ruby_script ruby file_name.rb 

You will get PATH and GEM_HOME with the following commands:

 echo $PATH echo $GEM_HOME 
+1
source

The question is about the linux environment, but this answer may help a Windows user who stumbles upon this in the future.

There are some Ruby packaging jewelry available here .

The most popular is OCRA (a one-armed Ruby application), which is available for both Gem and a standalone Ruby file, and will pack your Ruby project into a Windows executable.

0
source

All Articles