I've run into a strange problem with Ruby that I can't explain. I have the following script that grabs whatever code is currently in the clipboard, runs it through a syntax highlighter, then puts the new version BACK into the clipboard:
#!/usr/bin/ruby1.9.1
require 'coderay'
language = "auto";
if(ARGV.length > 0)
language = ARGV[0];
end
print("Using language: #{language} \n");
codeToHighlight = `xsel --clipboard`
highlightedCode = CodeRay.scan(codeToHighlight, language.intern()).div
IO.popen("xsel --clipboard", mode='w') do |io|
io.write highlightedCode
io.flush
end
The odd part is that if I run it directly within a terminal, it works fine. If I run it via "xterm -e", however, it doesn't work. I found this thread on another site that asked the same question, but the person never got an answer: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/138423
That person found that if they added a pause at the end of the script like so...
10000.times do
puts ""
end
...it works. Why is this? Is there a way to fix this? I tried rewriting the script so that the popen returns an IO object and I could manually call close, but that doesn't make a difference.