首先,Jruby的官方站点是http://jruby.org/,最详尽的资料都在那里。至于为什么选择JRuby,官方站点上列举了诸如jvm的普及以及性能等等优点,但我想最简单的回答就是,我喜欢用ruby编程,而大多数不再充电的老板还固守着java,对他们来说,相对于ruby,java这个词本身先产生了50%的安全感,所以这可能是比较贴近现实的选择。不过我今天想去倒腾倒腾这个东西,则完全是为了了解ruby的方方面面。
C:\>jruby --version
jruby 1.7.4 (1.9.3p392) 2013-05-16 2390d3b on Java HotSpot(TM) 64-Bit Server VM 1.6.0_38-b05 [Windows 7-amd64]
jruby -S gem list --local
jruby -S gem install rails mongrel jdbc-mysql activerecord-jdbcmysql-adapter
jruby -S rails new blog
cd blog
jruby -S rake -T
jruby -S rake db:create
jruby -S rake db:migrate
C:\>jirb
irb(main):001:0>
package example;
public class JavaMan {
public JavaMan() {
}
public void hello() {
System.out.println("Hello, I am a Java man!");
}
public void hello(String name){
System.out.println("Hello "+name+", I am a Java man!");
}
}
C:\DEMO>javac JavaMan.java -d .
require 'java'
java_import "example.JavaMan" #导入java类JavaMan
j=JavaMan.new
j.hello
j.hello "Jason"
C:\DEMO>jruby demo.rb
Hello, I am a Java man!
Hello Jason, I am a Java man!
也可以直接在jirb中调试ruby程序:
C:\DEMO>jirb
irb(main):001:0> java_import 'example.JavaMan'
=> [Java::Example::JavaMan]
irb(main):002:0> JavaMan.new.hello "Jason"
Hello Jason, I am a Java man!
=> nil
package example;
public interface JavaDog{
public void runs();
}
require 'java'
java_import "example.JavaDog" #导入java接口
class FastDog
include JavaDog
def runs
puts "I am running fast!"
end
end
FastDog.new.runs
C:\DEMO>jruby demo.rb
I am running fast!
require 'java'
require 'some.jar'
java_import "example.Person"
p=Person.new
p.name="Jason"
p.age=10
p.sex="Male"
begin
p.country="China"
rescue NoMethodError => e
puts "No country setter in Person bean"
end
puts p.getProfile
C:\DEMO>jruby demo.rb
No country setter in Person bean
Name:Jason Sex:Male Age:10