'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?



Solution 1:[1]

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>

Solution 2:[2]

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>

Solution 3:[3]

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.

Solution 4:[4]

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>

Solution 5:[5]

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

ennoremap <C-r> :!ruby % 

press ctrl+r then enter

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tallboy
Solution 2
Solution 3 Kashish Khullar
Solution 4 Dragonn steve
Solution 5 joox