How to run Ruby file on Sublime Text

2019-04-17 07:13发布

I have a file named add_and_power.rb as below, and want to run it on Sublime Text.

def add_and_power a,b
  (a+b)**(a+b)
end

puts "First number please? "
input1 = gets

puts "Second number please? "
input2 = gets

puts "The result is: ", add_and_power(input1.to_i, input2.to_i)

I run cmd+b, but it just displays,

First number please? 
Second number please? 
The result is: 
1
[Finished in 0.9s]

I want to input 2 and 3 to get the answer. How can I make Sublime Text 2 ask for inputs and give back an answer?

2条回答
走好不送
2楼-- · 2019-04-17 07:43

It is possible to run your programs when you need to have user input from the keyboard, but it isn't very nice.

When I do so, I need to input from a terminal that opens when I run Sublime, while also reading the response from the program at the bottom of the editor.

It is simply easier to run the program from the console/terminal.

So, the answer is, while it is possible to do so, there are concerns. You may need to use STDOUT.sync = true or STDOUT.flush to help manage the buffer with the OS, you have two thing to look at, while doing so... yuck.

It may not be the answer you are looking for, but as a developer, you should be comfortable running things from the console/terminal.

查看更多
祖国的老花朵
3楼-- · 2019-04-17 07:53

If you want to run code within ST2, check out the SublimeREPL plugin, available through Package Control. You can either use IRB or pry, which is a lot more powerful. You can use it as a classic REPL (think Clojure or LISP), and you can also transfer your code from one tab into the running REPL in another tab by selection, line range, or block.

In some of my tests the pry REPL doesn't handle input through gets very well, but I haven't played around with it that much. YMMV - Edit - As AGS mentions below, use my_var = $stdin.gets for interactive input within SublimeREPL Ruby.

I highly highly recommend SublimeREPL, as it's a really powerful tool, and is self-contained within ST2, so you don't have to keep flipping back and forth to your terminal, saving and reloading your programs.

查看更多
登录 后发表回答