DMelt:Programming/6 JRuby

From jWork.ORG
Jump to: navigation, search
Limitted access. Reguest membership or login to this link first if you are already a member
Contents

Using JRuby / Ruby

You can program in JRuby language JRuby as well. Here are a few Ruby tutorials:

You can program in JRuby language JRuby as well. As usual, create a JRuby script in the editor (with the extension *.rb) and run such scripts in the editor.

One important advantage of JRuby scripting is that programs (especially loops) in this language are faster then for Jython, and much faster than in BeanShell. First, let us show how to make a standard Java JFrame:

include Java
import javax.swing.JFrame

frame = JFrame.new("Hello Swing")
button = javax.swing.JButton.new("Klick Me!")
button.add_action_listener do  evt 
  javax.swing.JOptionPane.showMessageDialog(nil, <<EOS)
<html>Hello from <b><u>JRuby</u></b>.<br>
Button '#{evt.getActionCommand()}' clicked.
EOS
end

# Add the button to the frame
frame.get_content_pane.add(button)

# Show frame
frame.set_default_close_operation(JFrame::EXIT_ON_CLOSE)
frame.pack
frame.visible = true

Save this file in "example.rb" and run this script using the button Run.png on the toolbar of DataMelt. One can also use the [F8] key for fast execution of a script. You will see a pop-up JFrame. In case of an error, the DataMelt outputs error to bottom console.


JRuby and DataMelt

Let us show how to work with scientific libraries using JRuby.

Let us rewrite Jython/Python example of how to create a histogram and shown it using JRuby language. Our goal will be to rewrite this script [man:data:histograms#plotting_a_histogram showing H1D histogram].

First of all, one can use interactive JRubyShell of the IDE for prototyping and debugging. But our goal will be to write a script using the editor.

include_class Java::jhplot.HPlot
include_class Java::jhplot.H1D

c1=HPlot.new()
c1.setGTitle("Global labels: F_{2},  x_{&gamma;}  #bar{p}p F_{2}^{c#bar{c}}"); #put title
c1.visible()
c1.setAutoRange()

h1 = H1D.new("Simple1",100, -2, 2.0)
rand =java.util.Random.new()

print "Use of for loop in JRuby \n"
for i in 1..100
   puts "Value is => #{i}"
   h1.fill(rand.nextGaussian())
  end
c1.draw(h1)

Create a file "example.rb" with this code (the extension "rb" is very important!) and run this script as usual. To run this script, use the Run button [[File::Run.png]] on the toolbar of DataMelt. One can also use the [F8] key for fast execution of a script. In case of an error, the DataMelt outputs error to JRubyShell.

Java class imports

More information on this topic is in DMelt books