Thursday, May 31, 2012

Ruby, RVM, VIM and Sha-bang

Executing a Ruby script from within vim . . .

I heard that vim is the editor that Rubyists use. I wanted to find out how to execute a script from within the vim editor. Because I use RVM (ruby version manager), the usual !# (sha-bang) did not work but with a slight alteration, all ended well.

At the terminal command line, I switched to my Ruby of choice using RVM and then started vim to begin editing Sample.rb.
[ruby] rvm use 1.9.3
Using /Users/javapro/.rvm/gems/ruby-1.9.3-preview1
[ruby] vim Sample.rb
Here's the code I entered. It came from JumpStartLab
#!/usr/bin/env ruby
class Sample
  def hello
    puts "Hello, World"
  end
end

s = Sample.new
s.hello 
The first line contains my alteration of JumpStartLab's Ruby script. I added the !# (sha-bang) which contains the specific command used for executing a RVM managed Ruby.

Now, to run Sample.rb from within the vim editing session, press escape colon bang space percent enter. The vim editor will appear as below just before enter is pressed.
#!/usr/bin/env ruby
class Sample
  def hello
    puts "Hello, World"
  end
end

s = Sample.new
s.hello
~                                                                                                                                    
~                                                                                                                                    
~                                                                                                                                    
~                                                                                                                                    
:! %
The command entered in vim will cause vim to present the following on the screen which shows the result of executing the script.

Hello, World

Press ENTER or type command to continue