SlideShare a Scribd company logo
jRuby
The best of both worlds




                      Christopher Spring
@autonomous
Confessions of a... Rubyist
jRuby: The best of both worlds
Brief history of
Yukihiro “Matz” Matsumoto
Yukihiro “Matz” Matsumoto




“I wanted a scripting language that was more powerful
  than Perl, and more object-oriented than Python...”
“[We] need to focus on humans, on how humans
care about doing programming... We are the masters.
               They are the slaves.”
jRuby: The best of both worlds
“I hope to see Ruby help every programmer in
     the world be productive, and to enjoy
         programming, and to be happy.
This is the primary purpose of Ruby language”
A   primer
# booleans
truth = true
lies = false

# Strings
dude = 'Matz'
credo = "#{dude} is nice,
          so we are nice!"

# Numbers
42 ** 13
53.8 / 9
19 % 3
# Arrays
backpack = [6, 'apple', [true, some_object]]

# Hashes
hash = {
  true     => 'He loves me!',
  dude     => 'Must obey!',
  backpack => false
}

# symbols
cities = [:paris, :new_york, :johannesburg]
Wtf is a symbol?
coders = [
  { 'language' => 'ruby', 'location' => 'johannesburg' },
  { 'language' => 'java', 'location' => 'port elizabeth' },
  # ...
  { 'language' => 'ruby', 'location' => 'pretoria' }
]

                           # vs.

coders = [
  { :language => 'ruby', :location => 'johannesburg' },
  { :language => 'java', :location => 'port elizabeth' },
  # ...
  { :language => 'ruby', :location => 'pretoria' }
]
Cool, what about
    classes?
public Class Person {
  private String firstName, lastName;

    public Person(String firstName, String lastName){
      setFirstName(firstName);
      setLastName(lastName);
    }

    public String getFirstName(){
      return firstName;
    }

    public String getLastName(){
      return lastName;
    }

    public String setFirstName(String firstName){
      this.firstName = firstName;
    }

    public String setLastName(String lastName){
      this.lastName = lastName;
    }
}
class Person
  attr_accessor :first_name, :last_name

  def initialize(first_name, last_name)
    @first_name = first_name
    @last_name = last_name
  end
end
class Person
   attr_accessor :first_name, :last_name

   def initialize(first_name, last_name)
     @first_name = first_name
     @last_name = last_name
   end
 end



person            = Person.new( 'Nick', 'Cave')
person.first_name = 'Slick'
person.last_name = 'Nave'
puts "#{person.first_name} #{person.last_name}"
Btw, everything is an
      Object!
true.class() # => TrueClass
false.to_s() # => "false"

5.9.floor()   # => 5

3.times{ puts('Hello JUG!') }
# => Hello JUG!
# => Hello JUG!
# => Hello JUG!
module Earth




end
module Earth
  class Person
    attr_reader :first_name, :last_name

    def initialize(first_name, last_name)
      @first_name, @last_name = first_name, last_name
    end
  end
end
module Earth
  class Person
    attr_reader :first_name, :last_name

    def initialize(first_name, last_name)
      @first_name, @last_name = first_name, last_name
    end
  end
end




  chap = Earth::Person.new('Chandler', 'Bing')
  chap.first_name # => Chandler
module RepublicPersonnel
  def storm_trooper
    Earth::Person.new('Storm', 'Trooper')
  end
end

class CloningVat
  extend RepublicPersonnel
end
module RepublicPersonnel
  def storm_trooper
    Earth::Person.new('Storm', 'Trooper')
  end
end

class CloningVat
  extend RepublicPersonnel
end




#<Earth::Person @last_name="Trooper", @first_name="Storm">
CloningVat.storm_trooper
module TehForce
  def sense
    '... a disturbance in the force'
  end
end

module Earth
  class Person
    include TehForce
  end
end
module TehForce
  def sense
    '... a disturbance in the force'
  end
end

module Earth
  class Person
    include TehForce
  end
end



    farm_boy = Earth::Person.new('Luke', 'Skywalker')

    # => '... a disturbance in the force'
    farm_boy.sense
def some_days( something_happens )
  puts 'The sun rises'
  puts something_happens
  puts 'The sun sets'
end

def other_days( this_happens, and_that_happens)
  puts 'The sun rises'
  puts this_happens
  puts and_that_happens
  puts 'The sun sets'
end



    some_days 'I do some work'
    other_days 'I skip', 'I read a book'
def some_days( something_happens )
  puts 'The sun rises'
  puts something_happens
  puts 'The sun sets'
end
def some_days( something_happens )
  puts 'The sun rises'
  puts something_happens
  puts 'The sun sets'
end
def some_days( something_happens )
  puts 'The sun rises'
  puts something_happens
  puts 'The sun sets'
end



def some_days
  puts 'The sun rises'
  yield
  puts 'The sun sets'
end

some_days { puts 'I go to work' }

some_days do
  puts 'I skip'
  puts 'I read a book'
end
file = File.open('i <3 ruby.txt', 'w')
file.puts "... i really do!"
file.close
file = File.open('i <3 ruby.txt', 'w')
 file.puts "... i really do!"
 file.close




File.open('i <3 ruby.txt', 'w') do |file|
  file.puts "... i really do!"
end
Rubyists TATFT!
describe Calculator do
  before(:each) do
    @calc = Calculator.new
  end

  context 'Addition' do
    it 'returns 10 when adding 5 and 5'
      @calc.add(5,5).should == 10
    end

    it 'returns 0 when adding 5 and -5' do
      @calc.add(5,-5).should == 0
    end
  end
  # ...
end
Metaprogramming
class Person
  def initialize
    @height, @weight, @hair_color = 6.2, '70kg', 'brown'
  end

  %w(height weight hair).each do |property|
    define_method("#{property}") do
      i_var = self.instance_eval("@#{property}")
      i_var.to_s.upcase
    end
  end

  def method_missing(*args, &block)
    puts "I dont have #{args[0].to_s.gsub(/_/, ' ')}"
  end
end

p = Person.new
p.my_height       #   =>   6.2
p.my_weight       #   =>   70KG
p.my_hair_color   #   =>   BROWN
p.your_car_keys   #   =>   I dont have your car keys
A   primer
jRuby: The best of both worlds
jRuby: The best of both worlds
or....
Demo time!!
Interactive Ruby

 $ jirb
 jruby-1.6.7 :001 > require 'java'
  => true
 jruby-1.6.7 :001 > #...
Ackermann
class Ackermann
  def self.ack(m, n)
    return n + 1           if m.zero?
    return ack(m - 1, 1)   if n.zero?

    ack( m - 1, ack(m, n - 1) )
  end
end
include Rubeus::Swing

JFrame.new('Ackerizer') do |frame|
  frame.layout = java.awt.FlowLayout.new
  @m, @n = JTextField.new('3'),JTextField.new('10')

  JButton.new('->') do
    start = Time.now

    @result.text = Ackermann.ack(
      @m.text.to_i,
      @n.text.to_i
    ).to_s

    puts "#{Time.now - start}"
  end

  @result = JTextField.new 10

  frame.pack
  frame.show
end
class Ackermann
  def self.ack(m, n)
    return n + 1           if m.zero?
    return ack(m - 1, 1)   if n.zero?

    ack( m - 1, ack(m, n - 1) )
  end
end
class Ackermann
  def self.ack(m, n)
    return n + 1              if m.zero?
    return ack(m - 1, 1)      if n.zero?

    ack( m - 1, ack(m, n - 1) )
  end
end


public class Ackermann {
  public static int ack(int m, int n) {
    if (m == 0)
      return n + 1;

        if (n == 0)
          return ack(m - 1, 1);

        return ack(m - 1, ack(m, n - 1));
    }
}
include Rubeus::Swing

JFrame.new('Ackerizer') do |frame|
  frame.layout = java.awt.FlowLayout.new
  @m, @n = JTextField.new('3'),JTextField.new('10')

  JButton.new('->') do
    start = Time.now

    @result.text = Java::Ackermann.ack(
      @m.text.to_i,
      @n.text.to_i
    ).to_s

    puts "#{Time.now - start}"
  end

  @result = JTextField.new 10

  frame.pack
  frame.show
end
Method overloading
public class OverloadTypeChecker {
  public static String inspect(long value) {
    return "long";
  }

    public static String inspect(String value) {
      return "string";
    }

    public static String inspect(Object value) {
      return "object";
    }
}
require 'java'

java_import 'OverloadTypeChecker' do
  'OTC'
end

# jRuby happily handles the simple case
OTC.inspect(5)           # long
OTC.inspect('Helloooo!') # string
OTC.inspect([])          # object
public class BitLength {
  public int neededFor(int i) {
    return 32;
  }

    public int neededFor(long l) {
      return 64;
    }
}
# jRuby can be forced to use a specific overload
require 'java'
java_import 'BitLength'

bits = BitLength.new
bits.needed_for(1_000_000) # 64
# jRuby can be forced to use a specific overload
require 'java'
java_import 'BitLength'

bits = BitLength.new
bits.needed_for(1_000_000) # 64

# java_send
bits.java_send :neededFor, [Java::int], 1_000_000 # 32
# jRuby can be forced to use a specific overload
require 'java'
java_import 'BitLength'

bits = BitLength.new
bits.needed_for(1_000_000) # 64

# java_send
bits.java_send :neededFor, [Java::int], 1_000_000 # 32

# java_alias
class BitLength
  java_alias :needed_for_int, :neededFor, [Java::int]
end

bits.needed_for_int 1_000_000 # 32
# jRuby can be forced to use a specific overload
require 'java'
java_import 'BitLength'

bits = BitLength.new
bits.needed_for(1_000_000) # 64

# java_send
bits.java_send :neededFor, [Java::int], 1_000_000 # 32

# java_alias
class BitLength
  java_alias :needed_for_int, :neededFor, [Java::int]
end

bits.needed_for_int 1_000_000 # 32

# java_method
needed = bits.java_method :neededFor, [Java::int]
needed.call 1_000_000 # 32
... and more about
        types
public class TypeChecker{
  public static String check(Object o){
    return o.getClass().getName();
  }
}




require 'java'

ruby_array = [1, 2, 'Mushrooms', :sample]
java_array = ruby_array.to_java

# org.jruby.RubyArray
Java::TypeChecker.check( ruby_array )

# [Ljava.lang.Object;
Java::TypeChecker.check( java_array )

# org.jruby.RubyArray
Java::TypeChecker.check( java_array.to_a )
Sooo, what about those
   C extensions... ?
Awesome, but why?
• Cross platform GUI dev
• Performance
• Ruby interface to legacy code
• Use a ruby test framework
  (Seriously, they’re amazing!)
• Utilize java libraries
• Sneak ruby into a java shop
• Threading
jRuby: The best of both worlds
import org.jruby.embed.InvokeFailedException;
import org.jruby.embed.ScriptingContainer;

public class RubyFromJava {
  public static void main(String[] args) {
    ScriptingContainer container = new ScriptingContainer();

        container.runScriptlet("puts 'Java touched my Ruby'");
    }
}




                   $ java -cp jruby-complete.jar:. RubyFromJava
                   Java touched my Ruby
More Demos!!
http://pragprog.com/book/jruby/using-jruby
http://www.meetup.com/Code-Coffee-JHB/
http://www.meetup.com/RubyOnBeer/
Questions?
Ad

More Related Content

What's hot (20)

Ruby basics
Ruby basicsRuby basics
Ruby basics
Aditya Tiwari
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
sangam biradar
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
nikomatsakis
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
nikomatsakis
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
ESUG
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger
 
Implementações paralelas
Implementações paralelasImplementações paralelas
Implementações paralelas
Willian Molinari
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Giuseppe Arici
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
tarcieri
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
C4Media
 
Linux shell
Linux shellLinux shell
Linux shell
Kenny (netman)
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
PROIDEA
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
Lin Yo-An
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
Rodolfo Finochietti
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
André Faria Gomes
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
Mohammad Shaker
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
kwatch
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
nikomatsakis
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
nikomatsakis
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
ESUG
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
WebExpo
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger
 
Implementações paralelas
Implementações paralelasImplementações paralelas
Implementações paralelas
Willian Molinari
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
Giuseppe Arici
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
tarcieri
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
C4Media
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
PROIDEA
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
Lin Yo-An
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
Rodolfo Finochietti
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
Dhaval Dalal
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
kwatch
 

Similar to jRuby: The best of both worlds (20)

A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
Tchelinux
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
Duda Dornelles
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
Jano Suchal
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
.toster
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
Cloudera, Inc.
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
elliando dias
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
Groovy
GroovyGroovy
Groovy
Zen Urban
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
VictorSzoltysek
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
Cody Engel
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
Ígor Bonadio
 
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares DornellesA linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
A linguagem de programação Ruby - Robson "Duda" Sejan Soares Dornelles
Tchelinux
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
Duda Dornelles
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
HamletDRC
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
Jano Suchal
 
Attributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active recordAttributes Unwrapped: Lessons under the surface of active record
Attributes Unwrapped: Lessons under the surface of active record
.toster
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
Pavlo Baron
 
A tour on ruby and friends
A tour on ruby and friendsA tour on ruby and friends
A tour on ruby and friends
旻琦 潘
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
Joe Zulli
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
偉格 高
 
AST Transformations at JFokus
AST Transformations at JFokusAST Transformations at JFokus
AST Transformations at JFokus
HamletDRC
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
Arturo Herrero
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
VictorSzoltysek
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
Cody Engel
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
Edgar Suarez
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
Ígor Bonadio
 
Ad

Recently uploaded (20)

Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdfComplete Guide to Advanced Logistics Management Software in Riyadh.pdf
Complete Guide to Advanced Logistics Management Software in Riyadh.pdf
Software Company
 
Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025Splunk Security Update | Public Sector Summit Germany 2025
Splunk Security Update | Public Sector Summit Germany 2025
Splunk
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc Webinar: Consumer Expectations vs Corporate Realities on Data Broker...
TrustArc
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptxSpecial Meetup Edition - TDX Bengaluru Meetup #52.pptx
Special Meetup Edition - TDX Bengaluru Meetup #52.pptx
shyamraj55
 
TrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business ConsultingTrsLabs - Fintech Product & Business Consulting
TrsLabs - Fintech Product & Business Consulting
Trs Labs
 
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul Shares 5 Steps to Implement AI Agents for Maximum Business Efficien...
Noah Loul
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)Into The Box Conference Keynote Day 1 (ITB2025)
Into The Box Conference Keynote Day 1 (ITB2025)
Ortus Solutions, Corp
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Role of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered ManufacturingRole of Data Annotation Services in AI-Powered Manufacturing
Role of Data Annotation Services in AI-Powered Manufacturing
Andrew Leo
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Ad

jRuby: The best of both worlds

  • 1. jRuby The best of both worlds Christopher Spring
  • 7. Yukihiro “Matz” Matsumoto “I wanted a scripting language that was more powerful than Perl, and more object-oriented than Python...”
  • 8. “[We] need to focus on humans, on how humans care about doing programming... We are the masters. They are the slaves.”
  • 10. “I hope to see Ruby help every programmer in the world be productive, and to enjoy programming, and to be happy. This is the primary purpose of Ruby language”
  • 11. A primer
  • 12. # booleans truth = true lies = false # Strings dude = 'Matz' credo = "#{dude} is nice, so we are nice!" # Numbers 42 ** 13 53.8 / 9 19 % 3
  • 13. # Arrays backpack = [6, 'apple', [true, some_object]] # Hashes hash = { true => 'He loves me!', dude => 'Must obey!', backpack => false } # symbols cities = [:paris, :new_york, :johannesburg]
  • 14. Wtf is a symbol?
  • 15. coders = [ { 'language' => 'ruby', 'location' => 'johannesburg' }, { 'language' => 'java', 'location' => 'port elizabeth' }, # ... { 'language' => 'ruby', 'location' => 'pretoria' } ] # vs. coders = [ { :language => 'ruby', :location => 'johannesburg' }, { :language => 'java', :location => 'port elizabeth' }, # ... { :language => 'ruby', :location => 'pretoria' } ]
  • 16. Cool, what about classes?
  • 17. public Class Person { private String firstName, lastName; public Person(String firstName, String lastName){ setFirstName(firstName); setLastName(lastName); } public String getFirstName(){ return firstName; } public String getLastName(){ return lastName; } public String setFirstName(String firstName){ this.firstName = firstName; } public String setLastName(String lastName){ this.lastName = lastName; } }
  • 18. class Person attr_accessor :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end end
  • 19. class Person attr_accessor :first_name, :last_name def initialize(first_name, last_name) @first_name = first_name @last_name = last_name end end person = Person.new( 'Nick', 'Cave') person.first_name = 'Slick' person.last_name = 'Nave' puts "#{person.first_name} #{person.last_name}"
  • 20. Btw, everything is an Object!
  • 21. true.class() # => TrueClass false.to_s() # => "false" 5.9.floor() # => 5 3.times{ puts('Hello JUG!') } # => Hello JUG! # => Hello JUG! # => Hello JUG!
  • 23. module Earth class Person attr_reader :first_name, :last_name def initialize(first_name, last_name) @first_name, @last_name = first_name, last_name end end end
  • 24. module Earth class Person attr_reader :first_name, :last_name def initialize(first_name, last_name) @first_name, @last_name = first_name, last_name end end end chap = Earth::Person.new('Chandler', 'Bing') chap.first_name # => Chandler
  • 25. module RepublicPersonnel def storm_trooper Earth::Person.new('Storm', 'Trooper') end end class CloningVat extend RepublicPersonnel end
  • 26. module RepublicPersonnel def storm_trooper Earth::Person.new('Storm', 'Trooper') end end class CloningVat extend RepublicPersonnel end #<Earth::Person @last_name="Trooper", @first_name="Storm"> CloningVat.storm_trooper
  • 27. module TehForce def sense '... a disturbance in the force' end end module Earth class Person include TehForce end end
  • 28. module TehForce def sense '... a disturbance in the force' end end module Earth class Person include TehForce end end farm_boy = Earth::Person.new('Luke', 'Skywalker') # => '... a disturbance in the force' farm_boy.sense
  • 29. def some_days( something_happens ) puts 'The sun rises' puts something_happens puts 'The sun sets' end def other_days( this_happens, and_that_happens) puts 'The sun rises' puts this_happens puts and_that_happens puts 'The sun sets' end some_days 'I do some work' other_days 'I skip', 'I read a book'
  • 30. def some_days( something_happens ) puts 'The sun rises' puts something_happens puts 'The sun sets' end
  • 31. def some_days( something_happens ) puts 'The sun rises' puts something_happens puts 'The sun sets' end
  • 32. def some_days( something_happens ) puts 'The sun rises' puts something_happens puts 'The sun sets' end def some_days puts 'The sun rises' yield puts 'The sun sets' end some_days { puts 'I go to work' } some_days do puts 'I skip' puts 'I read a book' end
  • 33. file = File.open('i <3 ruby.txt', 'w') file.puts "... i really do!" file.close
  • 34. file = File.open('i <3 ruby.txt', 'w') file.puts "... i really do!" file.close File.open('i <3 ruby.txt', 'w') do |file| file.puts "... i really do!" end
  • 35. Rubyists TATFT! describe Calculator do before(:each) do @calc = Calculator.new end context 'Addition' do it 'returns 10 when adding 5 and 5' @calc.add(5,5).should == 10 end it 'returns 0 when adding 5 and -5' do @calc.add(5,-5).should == 0 end end # ... end
  • 37. class Person def initialize @height, @weight, @hair_color = 6.2, '70kg', 'brown' end %w(height weight hair).each do |property| define_method("#{property}") do i_var = self.instance_eval("@#{property}") i_var.to_s.upcase end end def method_missing(*args, &block) puts "I dont have #{args[0].to_s.gsub(/_/, ' ')}" end end p = Person.new p.my_height # => 6.2 p.my_weight # => 70KG p.my_hair_color # => BROWN p.your_car_keys # => I dont have your car keys
  • 38. A primer
  • 43. Interactive Ruby $ jirb jruby-1.6.7 :001 > require 'java' => true jruby-1.6.7 :001 > #...
  • 45. class Ackermann def self.ack(m, n) return n + 1 if m.zero? return ack(m - 1, 1) if n.zero? ack( m - 1, ack(m, n - 1) ) end end
  • 46. include Rubeus::Swing JFrame.new('Ackerizer') do |frame| frame.layout = java.awt.FlowLayout.new @m, @n = JTextField.new('3'),JTextField.new('10') JButton.new('->') do start = Time.now @result.text = Ackermann.ack( @m.text.to_i, @n.text.to_i ).to_s puts "#{Time.now - start}" end @result = JTextField.new 10 frame.pack frame.show end
  • 47. class Ackermann def self.ack(m, n) return n + 1 if m.zero? return ack(m - 1, 1) if n.zero? ack( m - 1, ack(m, n - 1) ) end end
  • 48. class Ackermann def self.ack(m, n) return n + 1 if m.zero? return ack(m - 1, 1) if n.zero? ack( m - 1, ack(m, n - 1) ) end end public class Ackermann { public static int ack(int m, int n) { if (m == 0) return n + 1; if (n == 0) return ack(m - 1, 1); return ack(m - 1, ack(m, n - 1)); } }
  • 49. include Rubeus::Swing JFrame.new('Ackerizer') do |frame| frame.layout = java.awt.FlowLayout.new @m, @n = JTextField.new('3'),JTextField.new('10') JButton.new('->') do start = Time.now @result.text = Java::Ackermann.ack( @m.text.to_i, @n.text.to_i ).to_s puts "#{Time.now - start}" end @result = JTextField.new 10 frame.pack frame.show end
  • 50. Method overloading public class OverloadTypeChecker { public static String inspect(long value) { return "long"; } public static String inspect(String value) { return "string"; } public static String inspect(Object value) { return "object"; } }
  • 51. require 'java' java_import 'OverloadTypeChecker' do 'OTC' end # jRuby happily handles the simple case OTC.inspect(5) # long OTC.inspect('Helloooo!') # string OTC.inspect([]) # object
  • 52. public class BitLength { public int neededFor(int i) { return 32; } public int neededFor(long l) { return 64; } }
  • 53. # jRuby can be forced to use a specific overload require 'java' java_import 'BitLength' bits = BitLength.new bits.needed_for(1_000_000) # 64
  • 54. # jRuby can be forced to use a specific overload require 'java' java_import 'BitLength' bits = BitLength.new bits.needed_for(1_000_000) # 64 # java_send bits.java_send :neededFor, [Java::int], 1_000_000 # 32
  • 55. # jRuby can be forced to use a specific overload require 'java' java_import 'BitLength' bits = BitLength.new bits.needed_for(1_000_000) # 64 # java_send bits.java_send :neededFor, [Java::int], 1_000_000 # 32 # java_alias class BitLength java_alias :needed_for_int, :neededFor, [Java::int] end bits.needed_for_int 1_000_000 # 32
  • 56. # jRuby can be forced to use a specific overload require 'java' java_import 'BitLength' bits = BitLength.new bits.needed_for(1_000_000) # 64 # java_send bits.java_send :neededFor, [Java::int], 1_000_000 # 32 # java_alias class BitLength java_alias :needed_for_int, :neededFor, [Java::int] end bits.needed_for_int 1_000_000 # 32 # java_method needed = bits.java_method :neededFor, [Java::int] needed.call 1_000_000 # 32
  • 57. ... and more about types
  • 58. public class TypeChecker{ public static String check(Object o){ return o.getClass().getName(); } } require 'java' ruby_array = [1, 2, 'Mushrooms', :sample] java_array = ruby_array.to_java # org.jruby.RubyArray Java::TypeChecker.check( ruby_array ) # [Ljava.lang.Object; Java::TypeChecker.check( java_array ) # org.jruby.RubyArray Java::TypeChecker.check( java_array.to_a )
  • 59. Sooo, what about those C extensions... ?
  • 60. Awesome, but why? • Cross platform GUI dev • Performance • Ruby interface to legacy code • Use a ruby test framework (Seriously, they’re amazing!) • Utilize java libraries • Sneak ruby into a java shop • Threading
  • 62. import org.jruby.embed.InvokeFailedException; import org.jruby.embed.ScriptingContainer; public class RubyFromJava { public static void main(String[] args) { ScriptingContainer container = new ScriptingContainer(); container.runScriptlet("puts 'Java touched my Ruby'"); } } $ java -cp jruby-complete.jar:. RubyFromJava Java touched my Ruby

Editor's Notes