Sergey
Sergey

Reputation: 11928

Running ruby code from vim

Is it possible after editing a ruby program in Vim to run it while still in the editor, not using the command line?

Upvotes: 11

Views: 5647

Answers (6)

joox
joox

Reputation: 47

Add this line in your '''vimrc''' and save your file

ennoremap <C-r> :!ruby % 

press ctrl+r then enter

Upvotes: -1

Dragonn steve
Dragonn steve

Reputation: 11

You can use this function.

function RunWith (command)
  execute "w"
  execute "!clear;" . a:command . " " . expand("%")
endfunction

And then, just create shortcut which is only works for ruby. You should to go to the ruby file and press this shortcut :)

autocmd FileType ruby nmap <Leader>e :call RunWith("ruby")<cr>

You can create shortcut for any file type. This is javascript example:

autocmd FileType js nmap <Leader>e :call RunWith("node")<cr>

Upvotes: 0

Tallboy
Tallboy

Reputation: 13467

This is an old question but I wanted to tweak the answer by @xavier

Put this in your .vimrc and you will be able to run the current ruby script without having to confirm hitting ENTER each time:

autocmd BufRead, *.rb nmap <leader>r :silent !{ruby %}<cr>

Upvotes: 2

Kashish Khullar
Kashish Khullar

Reputation: 424

Yes it is possible. For example lets say i want to write in a document word hello 100000 Now i won't do that manually but i will use ruby script and run it in vim. In terminal create a new file by typing vim script.rb Type this code:

10000.times do
       puts "hello"
end

Before exiting Press escape then type this:

:w ! ruby > testfile.txt

press enter What this will do is that it will run the script in the vim and add the returned string into the text file named testfile. Make sure you have the file in the same directory or you can specify the directory along with the name.

Upvotes: 0

Git.Coach
Git.Coach

Reputation: 3092

As an addition to @Xavier ’s solution I recommend binding it in the following way inside your .vimrc:

" run ruby code using leader-r only when inside a .rb file
au BufRead, *.rb nmap <leader>r :!ruby %<cr>

Upvotes: 1

Xavier T.
Xavier T.

Reputation: 42268

From Vim, you can run the current buffer with : :!ruby %

It might be helpful or not depending on your use case.

Similarly, you invoke any shell command by using :!command

Upvotes: 21

Related Questions