How to run Ruby file on Sublime Text - ruby

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.

Related

How do you set up tab autocompletion (for directories) in a Ruby CLI program?

Background on what I'm trying to do:
I've been teaching myself Ruby, and as a test project I'm creating a .csv converter. It's working well over all, but what I'm stuck on is allowing the user to easily select the file to be imported. Right now I prompt for the file path with the following code:
def find_original_path
puts "\nWhere is the file that you would like to convert?"
print ">> "
#original_path = gets.chomp
if File.exists?(#original_path)
# Verify that file is a .csv
check_original_type()
else
puts "\nSorry, that file doesn't seem to exist."
# Ask for a new path to file
find_original_path()
end
end
What I'd like to do:
So this works, but it requires that the user know the exact path to their .csv. What I'd prefer is to allow the user to use bash style auto-completion to find their file. Typing ~/ should start off at the user's home directory, and then hitting tab twice should list all available folders/files and so on.
What I've found:
Readline: My understanding is that this module only works for pre-set lists.
Thor: Awesome module, but seems to only work for providing deep argument functionality (e.g. git commands).
Shoes (and variants): Apparently green_shoes in particular has an easy way of doing this, but I'm not yet looking to put a GUI on this tool.
Ruby's Std-lib: I've gone through FileUtils, File, IO, etc...
Backticks and Open4: Makes sense for commands like ls, but not sure about directories.
In Sum:
Haven't found an answer that stood out to me in any of these. I feel like the answer to my problem is either more complex than I realized, or all of my reading has me missing something that's right under my nose. I'm hoping it's the latter, though please be gentle if it's really blindingly obvious :D
Any advice?

Rstudio difference between run and source

I am using Rstudio and not sure how options "run" and "source" are different.
I tried googling these terms but 'source' is a very common word and wasn't able to get good search results :(
Run and source have subtly different meanings. According to the RStudio documentation,
The difference between running lines from a selection and invoking
Source is that when running a selection all lines are inserted
directly into the console whereas for Source the file is saved to a
temporary location and then sourced into the console from there
(thereby creating less clutter in the console).
Something to be aware of, is that sourcing functions in files makes them available for scripts to use. What does this mean? Imagine you are trying to troubleshoot a function that is called from a script. You need to source the file containing the function, to make the changes available in the function be used when that line in the script is then run.
A further aspect of this is that you can source functions from your scripts. I use this code to automatically source all of the functions in a directory, which makes it easy to run a long script with a single run:
# source our functions
code.dir <- "c:\temp"
code.files = dir(code.dir, pattern = "[.r]")
for (file in code.files){
source(file = file.path(code.dir,file))
}
Sometimes, for reasons I don't understand, you will get different behavior depending on whether you select all the lines of code and press the run the button or go to code menu and chose 'source.' For example, in one specific case, writing a gplot to a png file worked when I selected all my lines of code but the write failed to when I went to the code menu and chose 'source.' However, if I choose 'Source with Echo,' I'm able to print to a png file again.
I'm simply reporting a difference here that I've seen between the selecting and running all your lines and code and going to code menu and choosing 'source,' at least in the case when trying to print a gplot to a png file.
An important implication of #AndyClifton's answer is:
Rstudio breakpoints work in source (Ctrl-Shift-S) but not in run (Ctrl-Enter)
Presumably the reason is that with run, the code is getting passed straight into the console with no support for a partial submission.
You can still use browser() though with run though.
print() to console is supported in debugSource (Ctrl-Shift-S) as well as run.
The "run" button simply executes the selected line or lines. The "source" button will execute the entire active document. But why not just try them and see the difference?
I also just discovered that the encoding used to read the function sourced can also be different if you source the file or if you add the function of the source file to your environment with Ctrl+Enter!
In my case there was a regex with a special character (ยต) in my function. When I imported the function directly (Ctrl+Enter) everything would work, while I had an error when sourcing the file containing this function.
To solve this issue I specified the encoding of the sourced file in the source function (source("utils.R", encoding = "UTF-8")).
Run will run each line of code, which means that it hits enter at the beginning of each line, which prints the output to the console. Source won't print anything unless you source with echo, which means that ggplot won't print to pngs, as another posted mentioned.
A big practical difference between run and source is that if you get an unaccounted for error in source it'll break you out of the code without finishing, whereas run will just pass the next line to the console and keep going. This has been the main practical difference I've seen working on cleaning up other people's scripts.
When using RSTudio u can press the run button in the script section - it will run the selected line.
Next to it you have the re - run button, to run the line again. and the source button next to it will run entire chuncks of code.
I found a video about this topic:
http://www.youtube.com/watch?v=5YmcEYTSN7k
Source/Source with echo is used to execute the whole file whereas Run as far as my personal experience goes executes the line in which your cursor is present.
Thus, Run helps you to debug your code. Watch out for the environment. It will display what's happening in the stack.
To those saying plots do not show. They won't show in Plots console. But you can definitely save the plot to disc using Source in RStudio. Using this snippet:
png(filename)
print(p)
dev.off()
I can confirm plots are written to disc. Furthermore print statements are also outputted to the console

Building a very simple wrapper for ANSI escape sequences

Maybe a mission impossible. Once upon a time I wrote a Ruby module SimpleDialog for text coloring in DOS windows. It does so by talking to the Windows APIs. Now I want to make it suitable for Mac OS as well, or even for the entire unix universe. Okay, just Terminal and xterm would satisfy my needs for the moment. ANSI escape sequences seem to be the appropriate weapons for the job. But using them I cannot always handle things as I would like to. Here is the functionality I try to realize:
def clear_screen
print "\e[H\e[2J\ec"
color( ... old colors stored in an instance variable ... )
end
The "\e[H\e[2J" part is the same as the clear command (that's how I've found this sequence [edit next day after some experiments: "\e[2J" does not erase any text sent before the "\e[H" sequence, even when it's visible on the screen]). Terminal and xterm only clear the visible part of the screen [issue 1]. The "\ec" part doesn't make sense for Terminal anymore, but this time xterm does succeed to clear the entire screen buffer. At doing so, it rings the bell [issue 2], while Terminal keeps silent. Since the "\ec" sequence resets the colors, the last settings have to be restored again. Not very elegant, altogether. The clear command submitted from the command line normally clears the entire screen buffer of xterm. However, it cannot wipe out the part that's left by my attempt to clear the screen by just sending "\e[H\e[2J" from Ruby.
def color( ... )
... too big to show here ...
end
The color method works almost fine, there's only one disappointment. In Windows, I can change the color of a rectangle without modifying the text that is already placed within it. I see no way how to do this by ANSI escape sequences [issue 3]. As a workaround I could memorize the text involved and restore it afterwards, of course. And this one is really puzzling me: the respons to "\e[6n" (report cursor position) is printed to the screen, with the last few
characters repeated after the command prompt. Can it be intercepted by Ruby [issue 4]?
The other methods are a piece of cake:
def shrink_window # to its original size
print "\e[9;0t"
end
def stretch_window # to the maximum size that fits on the screen
print "\e[9;1t"
end
def title(title = nil)
print "\e]2;#{title}\a"
end
def write(... text containing human-friendly color codes ...)
... trivial ...
end
MS-Windows allows me to get the current window title too, but I don't see real use for that (xterm doesn't listen at all when the title argument is an empty string, btw). The write method makes use of the color method. No problems here. So, in the end, four obstacles to overcome. Or to live with?
If you want help with all of these Mac OS and Unix terminal UI issues, try using the curses/ncurses libraries, through the Curses gem.
Since you already have a working Windows solution for this, you can create two classes that drive your dialog boxes. I suggest this because the presence of a curses library on Windows isn't always reliable or easy to install (see this question and its answers for examples of that problem in action). Keep your DOS implementation, then make an alternate that uses curses/ncurses. Then your code can chose which implementation to go with based on operating system or based on whether a working curses/ncurses library exists. Naturally, this path also simplifies adding even more methods of user interface later, too.

Program running not in order

I tried running this simple code:
puts 4
i = gets
puts i
It's "working", but the console asks for a string and just then it prints 4 and i
Add a flush call before gets:
$stdout.flush
Instead of explicitly calling $stdout.flush:
$stdout.sync = true
Works in order for me using ruby 1.8.7, 1.9.2 and ree. What version of ruby and operating system are you on?
What are you hoping to accomplish here ?
Normally the interpreter gathers all data before presenting you with the output. It's simply isnt bash :)
I guess you may be hit by output buffering. But your code example does not show how the program might "ask" for input, so I guess that you type answer just before ruby starts. Then your ruby program reads the input from input buffers, as the data is not read directly from the keyboard.
Are you sure that your problem is caused by exactly this code you have shown us?
Usually problems with data shown on terminal in wrong order are caused by using two different output streams: STDIN and STDERR for example. Each stream may decide to flush its data at different times.
if you want to make sure the text is displayed before something happens (as in this example) use the 'flush' command, as Yossi suggests.

How to use cbreak mode in Ruby terminal application?

In a small Ruby application, I'd like user input to be accepted without having to wait for a carriage return. My understanding is that cbreak mode needs to be enabled in order for the terminal to feed user input directly into the script.
I tried simply running x%[cbreak()] at the top of my script but that didn't work. I've also seen that it's possible to use (n)curses to achieve the same results, although that seems like overkill.
Does anybody have a suggestion on how to implement this?
Thanks
cbreak is a curses function call, so %x definitely doesn't apply (that is for executing shell commands). cbreak is defined in the standard curses library, so that would probably be your best bet.
See:
http://ruby-doc.org/stdlib/libdoc/curses/rdoc/classes/Curses.html#M000280
Edit: you might also check out Curses.getch
One solution which avoids having to use curses (which I find difficult to implement) is to use the shell's read command via %x. It doesn't feel right dipping into the shell to do something that seems like Ruby's STDIN should be responsible for, but it's simple and it works.
#! /usr/bin/ruby
puts "Please enter your first initial"
str = %x[read -s -n1 keypress; echo $keypress]
puts "Your first inital is " + str

Resources