RailsCasts - Ruby on Rails Screencasts

RailsCasts Pro episodes are now free!

Learn more or hide this

JRuby Basics

#376 JRuby Basics

Aug 30, 2012 | 10 minutes | Performance, Tools
JRuby is a polished and stable Ruby implementation. Here I show the basics of setting it up and executing Java from within Ruby. I also see how it compares with MRI at running threads.
Click to Play Video ▶
Tweet
  • Download:
  • source code Project Files in Zip (41 KB)
  • mp4 Full Size H.264 Video (28.6 MB)
  • m4v Smaller H.264 Video (12.8 MB)
  • webm Full Size VP8 Video (14 MB)
  • ogv Full Size Theora Video (23.3 MB)
Browse_code Browse Source Code

Resources

terminal
rbenv install jruby-1.7.0-preview2
rbenv shell jruby-1.7.0-preview2
ruby -v
jruby -v
jirb
irb
ruby swing.rb
ruby fib.rb
rbenv shell 1.9.3-p194
ruby fib.rb
rbenv shell jruby-1.7.0-preview2
gem install rails
# or jruby -S gem install rails
rails new blog
gem install sqlite3
rails g scaffold article name
rake db:migrate
rails s
time (rails runner nil)
console
h = java.util.HashMap.new
h.put(:foo, "bar")
h.get(:foo)
h[:foo]
h.java_class
javax.swing.JOptionPane.showMessageDialog(nil, "Hello World!")
Java::JavaxSwing::JOptionPane.show_message_dialog(nil, "Hello World!")
swing.rb
require "java"
java_import javax.swing.JFrame
java_import javax.swing.JButton
java_import javax.swing.JOptionPane
class HelloWorld < JFrame
 def initialize
 super "Example"
 setSize(150, 100)
 setDefaultCloseOperation(JFrame::EXIT_ON_CLOSE)
 setLocationRelativeTo(nil)
 button = JButton.new("Say Hello")
 add(button)
 button.addActionListener do |e|
 JOptionPane.showMessageDialog(nil, "Hello World")
 end
 setVisible(true)
 end
end
HelloWorld.new
fib.rb
def fib(n)
 n < 2 ? n : fib(n-1) + fib(n-2)
end
start = Time.now
1.upto(5).map do |n|
 Thread.new { puts "Thread #{n}: #{sleep(0.5)}" }
end.each(&:join)
puts "Time: #{Time.now - start}"
Gemfile
platform :jruby do
 gem 'activerecord-jdbcsqlite3-adapter'
 gem 'jruby-openssl'
 gem 'therubyrhino', group: :assets
end
platform :ruby do
 gem 'sqlite3'
end
loading

AltStyle によって変換されたページ (->オリジナル) /