Last updated October 13, 2008 20:29, by headius
Feedicon  

Most Duby code looks roughly like Ruby code with occasional type annotations. Here are a few quick examples.

Fibonacci

The code for fib is largely unchanged from the Ruby version, with the only obvious difference being the type declaration. Here, a Ruby symbol :fixnum is used. In the JVM backend for Duby, this ends up compiling to a primitive 32-bit int.

 def fib(a => :fixnum)
   if a < 2
     a
   else
     fib(a - 1) + fib(a - 2)
   end
 end

Note that the return value of this method, as all methods in Duby, is inferred from the exit points. The type inference engine will raise an error if multiple exit points have incompatible types.

Calling Java Libraries

Here's a short script showing importing and calling the java.lang.System class from a script. Two Java methods result from compiling this script: one for foo and one for the script body itself, which is compiled as the main() for the resulting .class file.

 import "System", "java.lang.System"
 
 def foo
   home = System.getProperty "java.home"
   System.setProperty "hello.world", "something"
   hello = System.getProperty "hello.world"
 
   puts home
   puts hello
 end
 
 puts "Hello world!"
 foo

The import syntax here is a bit cumbersome, and was only introduced to provide basic access to Java libraries. There's an open discussion about how to represent import in Duby.

Notice also that there are no types declared anywhere in this script. The types of 'home' and 'hello' within the 'foo' method are inferred to be java.lang.String from looking at the getProperty method on java.lang.System. Also, in the current Duby code, 'puts' is treated as a keyword that essentially does a System.out.println of the passed argument. This may or may not be part of final Duby; or puts may be an extension method applied to java.lang.Object, so it is always present to all scripts.

Constructing Objects

Because Ruby's standard for object construction is to call a "new" method on a target class, the Java backend uses the same syntax to invoke a constructor on a target type. Here an ArrayList and a StringBufer are constructed and manipulated. Note again the similarity to Ruby code; if the imports were gone, this script is perfectly valid Ruby code.

 import "StringBuffer", "java.lang.StringBuffer"
 import "ArrayList", "java.util.ArrayList"
 
 list = ArrayList.new
 sb = StringBuffer.new("Hello")
 sb.append(", world")
 list.add(sb)
 puts list

Note again that no types are actually declared here, and the types of 'list' and 'sb' are inferred from the results of constructing ArrayList and StringBuffer.

  • Mysql
  • Glassfish
  • Jruby
  • Rails
  • Nblogo
Terms of Use; Privacy Policy;
© 2010, Oracle Corporation and/or its affiliates
(revision 20120518.3c65429)
 
 
Close
loading
Please Confirm
Close