简体   繁体   中英

How to run Ruby file on Sublime Text

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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