SlideShare uma empresa Scribd logo
1 de 67
jRuby
The best of both worlds




                      Christopher Spring
@autonomous
Confessions of a... Rubyist
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.”
“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
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
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?

Mais conteúdo relacionado

Mais procurados

Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorialnikomatsakis
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02nikomatsakis
 
NativeBoost
NativeBoostNativeBoost
NativeBoostESUG
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: ServersidenessWebExpo
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger
 
Implementações paralelas
Implementações paralelasImplementações paralelas
Implementações paralelasWillian 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 2011Nick Sieger
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming LanguageGiuseppe 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 ProgrammingC4Media
 
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 itPROIDEA
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Lin Yo-An
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programmingRodolfo Finochietti
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8Dhaval Dalal
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Pythonkwatch
 

Mais procurados (20)

Ruby basics
Ruby basicsRuby basics
Ruby basics
 
Rustlabs Quick Start
Rustlabs Quick StartRustlabs Quick Start
Rustlabs Quick Start
 
Rust Mozlando Tutorial
Rust Mozlando TutorialRust Mozlando Tutorial
Rust Mozlando Tutorial
 
Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02Rust concurrency tutorial 2015 12-02
Rust concurrency tutorial 2015 12-02
 
NativeBoost
NativeBoostNativeBoost
NativeBoost
 
Douglas Crockford: Serversideness
Douglas Crockford: ServersidenessDouglas Crockford: Serversideness
Douglas Crockford: Serversideness
 
Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011Nick Sieger JRuby Concurrency EMRubyConf 2011
Nick Sieger JRuby Concurrency EMRubyConf 2011
 
Implementações paralelas
Implementações paralelasImplementações paralelas
Implementações paralelas
 
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
 
Swift Programming Language
Swift Programming LanguageSwift Programming Language
Swift Programming Language
 
Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)Concurrent programming with Celluloid (MWRC 2012)
Concurrent programming with Celluloid (MWRC 2012)
 
Rust: Unlocking Systems Programming
Rust: Unlocking Systems ProgrammingRust: Unlocking Systems Programming
Rust: Unlocking Systems Programming
 
Linux shell
Linux shellLinux shell
Linux shell
 
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
 
Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015Code Generation in PHP - PHPConf 2015
Code Generation in PHP - PHPConf 2015
 
Introduction to Rust language programming
Introduction to Rust language programmingIntroduction to Rust language programming
Introduction to Rust language programming
 
Introduction to Groovy
Introduction to GroovyIntroduction to Groovy
Introduction to Groovy
 
DRYing to Monad in Java8
DRYing to Monad in Java8DRYing to Monad in Java8
DRYing to Monad in Java8
 
C++ L11-Polymorphism
C++ L11-PolymorphismC++ L11-Polymorphism
C++ L11-Polymorphism
 
Fantastic DSL in Python
Fantastic DSL in PythonFantastic DSL in Python
Fantastic DSL in Python
 

Semelhante a jRuby: The best of both worlds

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 DornellesTchelinux
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming LanguageDuda Dornelles
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v RubyJano 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 scalaJoe 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 JFokusHamletDRC
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with GroovyArturo 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 1Troy Miles
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosEdgar Suarez
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma IntroduçãoÍgor Bonadio
 

Semelhante a 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
 
Ruby Programming Language
Ruby Programming LanguageRuby Programming Language
Ruby Programming Language
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
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
 
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)
 
Hw09 Hadoop + Clojure
Hw09   Hadoop + ClojureHw09   Hadoop + Clojure
Hw09 Hadoop + Clojure
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
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
 
Groovy
GroovyGroovy
Groovy
 
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
 
Functional Programming with Groovy
Functional Programming with GroovyFunctional Programming with Groovy
Functional Programming with Groovy
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
The Future of JVM Languages
The Future of JVM Languages The Future of JVM Languages
The Future of JVM Languages
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
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
 
Desarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutosDesarrollando aplicaciones web en minutos
Desarrollando aplicaciones web en minutos
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 

Último

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 

Último (20)

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

jRuby: The best of both worlds

  • 1. jRuby The best of both worlds Christopher Spring
  • 4.
  • 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.”
  • 9.
  • 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
  • 39.
  • 40.
  • 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
  • 61.
  • 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

Notas do Editor

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. 24 Feb 1993 Ruby was conceived\n25 Dec 1996 v 1.0 was released\n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. If the content of the object is important, use a string\nIf identity is important, use a symbol\n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. Ruby is truly object oriented\n
  21. Use modules as a namespace\n
  22. Use modules as a namespace\n
  23. Use modules as a namespace\n
  24. Extend class level behaviour\n
  25. Extend class level behaviour\n
  26. Notice that there isn&amp;#x2019;t a first and last_name!!\n
  27. Notice that there isn&amp;#x2019;t a first and last_name!!\n
  28. See the repetition?\n
  29. See the repetition?\n
  30. See the repetition?\n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. Google summer of code: \nCommon C extension API entry points translated\nand compiled in Java Native Interface\n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. Checkout RubyOnBeer: http://www.meetup.com/RubyOnBeer/\n
  65. \n