简体   繁体   English

从 vim 运行 ruby 代码

[英]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?在 Vim 中编辑 ruby 程序后是否可以在编辑器中运行它,而不是使用命令行?

From Vim, you can run the current buffer with: :!ruby %从 Vim 开始,您可以使用以下命令运行当前缓冲区:!ruby %

It might be helpful or not depending on your use case.根据您的用例,它可能会有所帮助或没有帮助。

Similarly, you invoke any shell command by using :!command同样,您可以使用:!command调用任何 shell 命令

This is an old question but I wanted to tweak the answer by @xavier这是一个老问题,但我想通过@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:把它放在你的.vimrc中,你就可以运行当前的 ruby 脚本,而不必每次都确认按 ENTER 键:

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

As an addition to @Xavier 's solution I recommend binding it in the following way inside your .vimrc :作为@Xavier 解决方案的补充,我建议在.vimrc中以下列方式绑定它:

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

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.例如,假设我想在文档中写入单词 hello 100000 现在我不会手动执行此操作,但我将使用 ruby 脚本并在 vim 中运行它。 In terminal create a new file by typing vim script.rb Type this code:在终端中通过键入 vim script.rb 创建一个新文件 键入以下代码:

10000.times do
       puts "hello"
end

Before exiting Press escape then type this:在退出之前按 Escape 然后输入:

: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.按下回车键,它会运行 vim 中的脚本,并将返回的字符串添加到名为 testfile 的文本文件中。 Make sure you have the file in the same directory or you can specify the directory along with the name.确保您将文件放在同一目录中,或者您可以指定目录和名称。

You can use this function.您可以使用此 function。

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

And then, just create shortcut which is only works for ruby.然后,只需创建仅适用于 ruby 的快捷方式。 You should to go to the ruby file and press this shortcut:)您应该将 go 到 ruby 文件并按此快捷方式:)

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

You can create shortcut for any file type.您可以为任何文件类型创建快捷方式。 This is javascript example:这是 javascript 示例:

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

Not really.并不真地。 Vim uses ruby, if linked to it at build time, as an extension language for internal consumption. Vim 使用 ruby,如果在构建时链接到它,作为内部使用的扩展语言。 You can pipe the buffer to an external ruby interpreter as Xavier T. points out.正如 Xavier T. 指出的那样,您可以将缓冲区 pipe 到外部ruby 解释器。

Add this line in your '''vimrc''' and save your file在你的'''vimrc'''中添加这一行并保存你的文件

ennoremap <C-r> :!ruby % 

press ctrl+r then enter按 ctrl+r 然后输入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM