SlideShare ist ein Scribd-Unternehmen logo
1 von 104
Downloaden Sie, um offline zu lesen
Ruby for Java
Programmers
Mike Bowler
President, Gargoyle Software Inc.
Why learn another
language?
Why Ruby?
Timeline: 1993 to
2000
Created in 1993 by
Yukihiro "Matz"
Matsumoto
Ruby was popular in
Japan but unknown
everywhere else
All documentation
was written in
Japanese
Timeline: 2000-
2004
First English language
book published in 2000
A lot of interest in the
Agile development
community but mostly
unknown elsewhere
Timeline: 2004-
today
The Ruby on Rails
framework has pushed
ruby into the spotlight
This is the “killer app”
What influenced it?
Terminology
Early
Late
Static
Dynamic
Strong
Weak
Defining strong/weak
typing
Strong typing
Objects are of a specific type and will not be
converted automatically
Java: “4”/2 results in a compile error
Weak typing
Objects can be converted under the covers at
any time
Perl: ‘4’/2 => 2
Ruby is strongly typed
Early/late
bindingEarly binding (aka static binding)
All method invocations must be defined at compile
time
Java: foo.getUser()
Late binding (aka dynamic binding)
The runtime does not check that a given method
exists until an attempt to invoke it
Smalltalk: foo user.
Ruby uses late binding
Similarities
Like Java, Ruby...
runs on a virtual machine
is garbage collected
is object oriented (although to different
degrees)
Differences
Everything is an object
Java
string = String.valueOf(1);
Ruby
string = 1.to_s()
Primitive
Object
Differences
Many things that you would expect to be
keywords are actually methods
throw new IllegalArgumentException("oops");
raise TypeError.new("oops")
Keywords
Methods
Differences
Some syntax optional unless the result is
ambiguous
These statements are equivalent
puts("foo");
puts "foo"
Idiomatic (better) style
Differences
Classes are real
objects
They’re instances of
Class
Class methods can
be overridden
class ZebraCage < Cage
attr_accessor :capacity
@@allCages = Array.new
def initialize maximumZebraCount
@capacity = maximumZebraCount
@@allCages << self
end
private
def clean_cage
# do some stuff here
end
end
cage = ZebraCage.new 10
puts cage.capacity
Multiline if
if name.nil?
do_something
end
Multiline if
if name.nil?
do_something
end
Notice the
question mark
With an else
if name.nil?
do_something
else
something_else
end
Single line if
if name.nil?
do_something
end
do_something if name.nil?
Both kinds of
unlessif name.nil?
do_something
end
do_something if name.nil?
unless name.nil?
do_something
end
do_something unless name.nil?
Dangerous methods
name = " foo "
name.strip
name.strip!
Returns a new string.
Doesn’t modify name.
Modifies name
and returns that.
Dangerous!
Philosophy
Java focuses on building blocks
You can build whatever you want with the
pieces
Ruby focuses on solving problems
Things you do frequently should be concise
Initializing
arraysList<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
Same only ruby
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list = Array.new
list << 'foo'
list << 'bar'
[]
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list = Array.new
list << 'foo'
list << 'bar'
list = ['foo', 'bar']
%w()
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
list = Array.new
list << 'foo'
list << 'bar'
list = ['foo', 'bar']
list = %w(foo bar)
In fairness to
java...List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
List<String> list = Arrays.asList("foo", "bar");
list = Array.new
list << 'foo'
list << 'bar'
list = ['foo', 'bar']
list = %w(foo bar)
Same idea with
hashes
Map<String,String> map
= new HashMap<String,String>();
map.put("foo", "one");
map.put("bar", "two");
map = {'foo' => 'one', 'bar' => 'two'}
Special case for
Hash
hash = {:a => 5, :b => 3}
do_stuff 30, hash
do_stuff 100, :a => 5, :b => 3
Regular
Expressions
Pattern pattern = Pattern.compile("^s*(.+)s*$");
Matcher matcher = pattern.matcher(line);
if( matcher.matches() ) {
doSomething();
}
Regular
Expressions
Pattern pattern = Pattern.compile("^s*(.+)s*$");
Matcher matcher = pattern.matcher(line);
if( matcher.matches() ) {
doSomething();
}
do_something if line =~ /^s*(.+)s*$/
Nil and Null
Java’s nullJava’s null Ruby’s nilRuby’s nil
Absence of an object An instance of NilClass
if( a != null ) {...} unless a.nil? {...}
null.toString() -> NPE nil.to_s -> “”
null.getUser() ->
Exception in thread "main"
java.lang.NullPointerException
nil.get_user ->
NoMethodError: undefined method
‘get_user’ for nil:NilClass
Implications of
late binding
Method dispatch is quite different
Ruby makes a distinction between “messages”
that are sent to an object and the “methods”
that get dispatched
Message != Method
What if there isn’t a
method for the
specified message?
method_missing
example from
ActiveRecord
user = Users.find_by_name(name)
user = Users.find(:first,
:conditions => [ "name = ?", name])
Creating proxy
objects
Mock object for testing
Proxy object to allow distributed objects across
machines
Wrapper to record usage of a given object
Implementing a
proxyclass Proxy
def method_missing name, *args, &proc
puts name,args
end
end
Implementing a
proxyclass Proxy
def method_missing name, *args, &proc
puts name,args
end
end
Proxy.new.foo_bar ‘a’
Proxy.new.to_s
Dispatches to
method_missing
Doesn’t go to
method_missing
Overriding to_s
class Proxy
def method_missing name, *args, &proc
puts name,args
end
def to_s
method_missing :to_s, []
end
end
=•===•=~•__id__•_send__•class•clone•dclone
display•dup•enum_for•eql?•equal?•extend freeze
frozen?•hash•id•inspect•instance_eval instance_of?
instance_variable_defined•instance_variable_get
instance_variable_get•instance_variable_set
instance_variable_set•instance_variables•is_a?
kind_of?•method•methods•new•nil?•object_id
private_methods•protected_methods•public_methods
remove_instance_variable•respond_to?•send
singleton_method_added•singleton_method_removed
singleton_method_undefined•singleton_methods•taint
tainted?•to_a•to_enum•to_s•to_yaml
to_yaml_properties•to_yaml_style•type•untaint
Implementing a proxy
class Proxy
instance_methods.each do |method|
undef_method method unless method =~ /^__/
end
def method_missing name, *args, &proc
puts name,args
end
end
Proxy.new.to_s
Unix was not designed to stop people
from doing stupid things, because that
would also stop them from doing
clever things.
—Doug Gwyn
Cultural
differences about
type
Java is very focused on the types of objects
Is the object an instance of a specific class?
Or does it implement a specific interface?
Ruby is focused on the behaviour
Does the object respond to a given message?
Types
public void foo( ArrayList list ) {
list.add("foo");
}
def foo list
list << 'foo'
end
What’s the type?
What’s the type?
Duck typing
def foo list
list << 'foo'
end
If list is a String
=> ‘foo’
If list is an Array
=> [‘foo’]
If list is an IO
=> string will be written to stream
Duck typing
Duck typing implies that an object is
interchangeable with any other object that
implements the same interface, regardless of
whether the objects have a related inheritance
hierarchy. -- Wikipedia
"If it walks like a duck and quacks like a duck,
it must be a duck." -- Pragmatic Dave Thomas
How does this
change how we
think of types?
think of types?
think of types?
Overflow conditions
int a = Integer.MAX_VALUE;
System.out.println(" a="+a);
System.out.println("a+1="+(a+1));
a=2147483647
a+1= ??
Overflow conditions
int a = Integer.MAX_VALUE;
System.out.println(" a="+a);
System.out.println("a+1="+(a+1));
a=2147483647
a+1=-2147483648
oops
Overflow in ruby?
number = 1000
1.upto(4) do
puts "#{number.class} #{number}"
number = number * number
end
Fixnum 1000
Fixnum 1000000
Bignum 1000000000000
Bignum 1000000000000000000000000
Closures
A closure is a function that is evaluated in an
environment containing one or more bound variables.
When called, the function can access these variables.
The explicit use of closures is associated with functional
programming and with languages such as ML and Lisp.
Constructs such as objects in other languages can also
be modeled with closures.
-- Wikipedia
Closures
A closure is a block of code that you can
manipulate and query
In Ruby we call them blocks or Procs
A block is a pure closure
A Proc is a block wrapped as an object
We generally use the terms block and Proc
interchangeably
Closures
multiplier = 5
block = lambda {|number| puts number * multiplier }
A block
An instance
of Proc
lambda() is a
method to convert
blocks into Procs
Closures
multiplier = 5
block = lambda {|number| puts number * multiplier }
Parameter
to the block
Closures
multiplier = 5
block = lambda {|number| puts number * multiplier }
Able to access variables
from outside the block
Proc’s
multiplier = 5
block = lambda {|number| puts number * multiplier }
block.call 2
block.arity
prints 10
returns number of parameters
that the block takes. 1 in this case
Blocks as
parameters
multiplier = 5
1.upto(3) {|number| puts number * multiplier }
=> 5
=> 10
=> 15
Same block
as before
Called once for each time
through the loop
Alternate syntax
multiplier = 5
1.upto(3) {|number| puts number * multiplier }
1.upto(3) do |number|
puts number * multiplier
end
Equivalent
Why are closures
significant?
Presence of closures in a language completely
changes the design of the libraries
Closure based libraries generally result in
significantly less code
// Read the lines and split them into columns
List<String[]> lines= new ArrayList<String[]>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("people.txt"));
String line = reader.readLine();
while( line != null ) {
lines.add( line.split("t") );
}
}
finally {
if( reader != null ) {
reader.close();
}
}
// then sort
Collections.sort(lines, new Comparator<String[]>() {
public int compare(String[] one, String[] two) {
return one[1].compareTo(two[1]);
}
});
// then write them back out
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("people.txt") );
for( String[] strings : lines ) {
StringBuilder builder = new StringBuilder();
for( int i=0; i<strings.length; i++ ) {
if( i != 0 ) {
builder.append("t");
}
builder.append(strings[i]);
}
}
}
finally {
if( writer != null ) {
writer.close();
}
}
# Load the data
lines = Array.new
IO.foreach('people.txt') do |line|
lines << line.split
end
# Sort and write it back out
File.open('people.txt', 'w') do |file|
lines.sort {|a,b| a[1] <=> b[1]}.each do |array|
puts array.join("t")
end
end
Closure File
Example
file = File.new(fileName,'w')
begin
file.puts ‘some content’
rescue
file.close
end
Closure File
Example
file = File.new(fileName,'w')
begin
file.puts ‘some content’
rescue
file.close
end Only one line of
business logic
Closure File
Example
file = File.new(fileName,'w')
begin
file.puts ‘some content’
rescue
file.close
end
File.open(fileName,'w') do |file|
file.puts ‘some content’
end
Ruby file IO
sample
# Load the data
lines = Array.new
IO.foreach('people.txt') do |line|
lines << line.split
end
# Sort and write it back out
File.open('people.txt', 'w') do |file|
lines.sort {|a,b| a[1] <=> b[1]}.each do |array|
puts array.join("t")
end
end
Closure-like things
in Java
final String name = getName();
new Thread( new Runnable() {
public void run() {
doSomething(name);
}
}).start();
Only one line of
business logic
Closures for
Java?
There are a couple of proposals being debated for
Java7
Unclear whether any of them will be accepted
In the past, Sun’s position has been that closures
didn’t make sense at this point in Java’s evolution
public static void main(String[] args) {
int plus2(int x) { return x+2; }
int(int) plus2b = plus2;
System.out.println(plus2b(2));
}
Inheriting
behaviour from
multiple places
C++ has multiple inheritance
Java has interfaces
Ruby has mixins
C++ : multiple
inheritance
Java :
inheritance
Ruby : mixins
Mixins
Cannot be instantiated
Can be mixed in
Enumerable
class Foo
include Enumerable
def each &block
block.call 1
block.call 2
block.call 3
end
end
module Enumerable
def collect
array = []
each do |a|
array << yield(a)
end
array
end
end
Enumerable
class Foo
include Enumerable
def each &block
block.call 1
block.call 2
block.call 3
end
end
module Enumerable
def collect
array = []
each do |a|
array << yield(a)
end
array
end
end
Enumerable
Requires that the class implement each()
For max, min and sort the <=> operator is also
needed
Adds many methods for modifying, searching, sorting
the items
all?, any?, collect, detect, each_cons, each_slice,
each_with_index, entries, enum_cons, enum_slice,
enum_with_index, find, find_all, grep, include?,
inject, map, max, member?, min, partition, reject,
select, sort, sort_by, to_a, to_set, zip
Reopening classes
class Foo
def one
puts 'one'
end
end
Reopening classes
class Foo
def one
puts 'one'
end
end
class Foo
def two
puts 'two'
end
end
Reopening
the same class
Reopening classes
class Foo
def one
puts 'one'
end
end
class Foo
def one
puts '1'
end
end
Replacing, not
adding a method
Reopening core
classesclass String
def one
puts 'one'
end
end
We reopened
a CORE class
and modified it
Metaprogramming
Metaprogramming is the writing of computer
programs that write or manipulate other
programs (or themselves) as their data. In many
cases, this allows programmers to get more done
in the same amount of time as they would take to
write all the code manually.
-- Wikipedia
What changes can
we make at
runtime?
Anything we can hand code, we can
programmatically do
Because of late binding, EVERYTHING
happens at runtime
attr_accessor
class Foo
attr_accessor :bar
end
class Foo
def bar
@bar
end
def bar=(newBar)
@bar = newBar
end
end
Getter
Setter
class Foo
def self.attr_accessor name
module_eval <<-DONE
def #{name}()
@#{name}
end
def #{name}=(newValue)
@#{name} = newValue
end
DONE
end
my_attr_accessor :bar
end
Possible
implementation of
attr_accessor
class Foo
def self.attr_accessor name
module_eval <<-DONE
def #{name}()
@#{name}
end
def #{name}=(newValue)
@#{name} = newValue
end
DONE
end
my_attr_accessor :bar
end
Possible
implementation of
attr_accessor
“Here Doc”
Evaluates to
String
class Foo
def self.attr_accessor name
module_eval <<-DONE
def #{name}()
@#{name}
end
def #{name}=(newValue)
@#{name} = newValue
end
DONE
end
my_attr_accessor :bar
end
Possible
implementation of
attr_accessor
String
substitution
class Foo
def self.attr_accessor name
module_eval <<-DONE
def #{name}()
@#{name}
end
def #{name}=(newValue)
@#{name} = newValue
end
DONE
end
my_attr_accessor :bar
end
Possible
implementation of
attr_accessor
Executes the string
in the context of
the class
Result
class Foo
def bar
@bar
end
def bar=(newBar)
@bar = newBar
end
end
ActiveRecord
class ListItem < ActiveRecord::Base
belongs_to :amazon_item
acts_as_taggable
acts_as_list :scope => :user
end
Date :: once
def once(*ids) # :nodoc:
for id in ids
module_eval <<-"end;", __FILE__, __LINE__
alias_method :__#{id.to_i}__, :#{id.to_s}
private :__#{id.to_i}__
def #{id.to_s}(*args, &block)
if defined? @__#{id.to_i}__
@__#{id.to_i}__
elsif ! self.frozen?
@__#{id.to_i}__ ||= __#{id.to_i}__(*args, &block)
else
__#{id.to_i}__(*args, &block)
end
end
end;
end
end
ObjectSpace
ObjectSpace.each_object do |o|
puts o
end
ObjectSpace.each_object(String) do |o|
puts o
end
ObjectSpace
ObjectSpace.each_object do |o|
puts o
end
ObjectSpace.each_object(String) do |o|
puts o
end
All objects
Only Strings
Continuations
A snapshot of the call stack that
the application can revert to at
some point in the future
Why
continuations?
To save the state of the application across
reboots of the VM
To save the state of the application across
requests to a web server
Seaside (smalltalk) does this today
Downsides
Only supported in one implementation of
Ruby
Will be removed from the language in Ruby
2.0
Implementations
Ruby 1.8.x - “reference implementation” in C
Ruby 1.9 - Next version of C interpreter
Rubinius - Ruby in Ruby (sort-of)
Cardinal - Ruby on Parrot
Iron Ruby - Ruby on the DLR (Microsoft)
Ruby.NET - Ruby on the CLR
JRuby - Ruby on the JVM (Sun)
Implementations
Ruby 1.8.x - “reference implementation” in C
Ruby 1.9 - Next version of C interpreter
Rubinius - Ruby in Ruby (sort-of)
Cardinal - Ruby on Parrot
Iron Ruby - Ruby on the DLR (Microsoft)
Ruby.NET - Ruby on the CLR
JRuby - Ruby on the JVM (Sun)
JRuby
Runs on the Java Virtual Machine (JVM)
Full implementation of the Ruby language
Supported by Sun
Runs many benchmarks faster than the 1.8
reference implementation (written in C)
Able to easily call out to Java code
Ruby on Rails
Web application framework
Sweet spot - web application talking to a single
relational database
Allows very rapid development of web apps
Who’s using
rails?
Amazon • BBC • Cap Gemini
Chicago Tribune • Barclays • BPN • Cisco
CNET Electronic Arts • IBM • John Deere
JP Morgan Chase • LA Times • Limewire
Linked In • NASA • NBC • New York Times
Oakley • Oracle • Orbitz • Turner Media
twitter.com • Siemens • ThoughtWorks Yahoo!
JRuby on Rails?
Yes! You can run a rails application on JRuby
in a servlet container
Goldspike is the servlet that dispatches to rails
Tested on WebLogic, WebSphere, GlassFish,
Jetty, Tomcat
Warbler is the packaging tool that makes the
WAR
Supported on: WebLogic, WebSphere,
GlassFish, Jetty, Tomcat
Recap
Learning a new language will make you better
with all the languages you know
Ruby has a much more concise syntax which
means that it takes much less code to solve the
same problems
Ruby is able to run on the JVM which makes it an
option for shops with heavy investments in J2EE
infrastructure
Recap
Everything is an object
The language is extremely malleable
New classes/methods can be created on the
fly
Existing classes can be modified at any time
Contacting me
Mike Bowler
mbowler@GargoyleSoftware.com
www.GargoyleSoftware.com (company)
www.SphericalImprovement.com (blog)
Interested in learning more about how Ruby and
Java can coexist in your company? Just ask me.

Weitere ähnliche Inhalte

Was ist angesagt?

Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayProtocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayAlexis Gallagher
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard LibrarySantosh Rajan
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8Garth Gilmour
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of FlatteryJosé Paumard
 
Java best practices
Java best practicesJava best practices
Java best practicesRay Toal
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language ComparisonRobert Bachmann
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonSiddhi
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 

Was ist angesagt? (18)

Java 8 ​and ​Best Practices
Java 8 ​and ​Best PracticesJava 8 ​and ​Best Practices
Java 8 ​and ​Best Practices
 
Protocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That WayProtocols with Associated Types, and How They Got That Way
Protocols with Associated Types, and How They Got That Way
 
The Swift Compiler and Standard Library
The Swift Compiler and Standard LibraryThe Swift Compiler and Standard Library
The Swift Compiler and Standard Library
 
10 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 810 Sets of Best Practices for Java 8
10 Sets of Best Practices for Java 8
 
Andy On Closures
Andy On ClosuresAndy On Closures
Andy On Closures
 
Getting rid of backtracking
Getting rid of backtrackingGetting rid of backtracking
Getting rid of backtracking
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
Ruby_Basic
Ruby_BasicRuby_Basic
Ruby_Basic
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Clojure 7-Languages
Clojure 7-LanguagesClojure 7-Languages
Clojure 7-Languages
 
Java best practices
Java best practicesJava best practices
Java best practices
 
C# / Java Language Comparison
C# / Java Language ComparisonC# / Java Language Comparison
C# / Java Language Comparison
 
Javascript
JavascriptJavascript
Javascript
 
Creating Domain Specific Languages in Python
Creating Domain Specific Languages in PythonCreating Domain Specific Languages in Python
Creating Domain Specific Languages in Python
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
ppt18
ppt18ppt18
ppt18
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 
ppt9
ppt9ppt9
ppt9
 

Ähnlich wie Rubyforjavaprogrammers 1210167973516759-9

Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Henry S
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmersamiable_indian
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Agapornis Mansos - www.criadourosudica.blogspot.com
Agapornis Mansos - www.criadourosudica.blogspot.comAgapornis Mansos - www.criadourosudica.blogspot.com
Agapornis Mansos - www.criadourosudica.blogspot.comAntonio Silva
 
Paulo Freire Pedagpogia 1
Paulo Freire Pedagpogia 1Paulo Freire Pedagpogia 1
Paulo Freire Pedagpogia 1Alejandra Perez
 
Washington Practitioners Significant Changes To Rpc 1.5
Washington Practitioners Significant Changes To Rpc 1.5Washington Practitioners Significant Changes To Rpc 1.5
Washington Practitioners Significant Changes To Rpc 1.5Oregon Law Practice Management
 

Ähnlich wie Rubyforjavaprogrammers 1210167973516759-9 (20)

Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2Code for Startup MVP (Ruby on Rails) Session 2
Code for Startup MVP (Ruby on Rails) Session 2
 
Ruby
RubyRuby
Ruby
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 
test ppt
test ppttest ppt
test ppt
 
ppt30
ppt30ppt30
ppt30
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmers
 
ppt21
ppt21ppt21
ppt21
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt17
ppt17ppt17
ppt17
 
name name2 n
name name2 nname name2 n
name name2 n
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
MMBJ Shanzhai Culture
MMBJ Shanzhai CultureMMBJ Shanzhai Culture
MMBJ Shanzhai Culture
 
Agapornis Mansos - www.criadourosudica.blogspot.com
Agapornis Mansos - www.criadourosudica.blogspot.comAgapornis Mansos - www.criadourosudica.blogspot.com
Agapornis Mansos - www.criadourosudica.blogspot.com
 
LoteríA Correcta
LoteríA CorrectaLoteríA Correcta
LoteríA Correcta
 
Paulo Freire Pedagpogia 1
Paulo Freire Pedagpogia 1Paulo Freire Pedagpogia 1
Paulo Freire Pedagpogia 1
 
Washington Practitioners Significant Changes To Rpc 1.5
Washington Practitioners Significant Changes To Rpc 1.5Washington Practitioners Significant Changes To Rpc 1.5
Washington Practitioners Significant Changes To Rpc 1.5
 

Mehr von sagaroceanic11

Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reportssagaroceanic11
 
Module 20 mobile forensics
Module 20 mobile forensicsModule 20 mobile forensics
Module 20 mobile forensicssagaroceanic11
 
Module 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimesModule 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimessagaroceanic11
 
Module 18 investigating web attacks
Module 18 investigating web attacksModule 18 investigating web attacks
Module 18 investigating web attackssagaroceanic11
 
Module 17 investigating wireless attacks
Module 17 investigating wireless attacksModule 17 investigating wireless attacks
Module 17 investigating wireless attackssagaroceanic11
 
Module 04 digital evidence
Module 04 digital evidenceModule 04 digital evidence
Module 04 digital evidencesagaroceanic11
 
Module 03 searching and seizing computers
Module 03 searching and seizing computersModule 03 searching and seizing computers
Module 03 searching and seizing computerssagaroceanic11
 
Module 01 computer forensics in todays world
Module 01 computer forensics in todays worldModule 01 computer forensics in todays world
Module 01 computer forensics in todays worldsagaroceanic11
 
Virtualisation with v mware
Virtualisation with v mwareVirtualisation with v mware
Virtualisation with v mwaresagaroceanic11
 
Virtualisation overview
Virtualisation overviewVirtualisation overview
Virtualisation overviewsagaroceanic11
 
Introduction to virtualisation
Introduction to virtualisationIntroduction to virtualisation
Introduction to virtualisationsagaroceanic11
 
2 the service lifecycle
2 the service lifecycle2 the service lifecycle
2 the service lifecyclesagaroceanic11
 
1 introduction to itil v[1].3
1 introduction to itil v[1].31 introduction to itil v[1].3
1 introduction to itil v[1].3sagaroceanic11
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overviewsagaroceanic11
 

Mehr von sagaroceanic11 (20)

Module 21 investigative reports
Module 21 investigative reportsModule 21 investigative reports
Module 21 investigative reports
 
Module 20 mobile forensics
Module 20 mobile forensicsModule 20 mobile forensics
Module 20 mobile forensics
 
Module 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimesModule 19 tracking emails and investigating email crimes
Module 19 tracking emails and investigating email crimes
 
Module 18 investigating web attacks
Module 18 investigating web attacksModule 18 investigating web attacks
Module 18 investigating web attacks
 
Module 17 investigating wireless attacks
Module 17 investigating wireless attacksModule 17 investigating wireless attacks
Module 17 investigating wireless attacks
 
Module 04 digital evidence
Module 04 digital evidenceModule 04 digital evidence
Module 04 digital evidence
 
Module 03 searching and seizing computers
Module 03 searching and seizing computersModule 03 searching and seizing computers
Module 03 searching and seizing computers
 
Module 01 computer forensics in todays world
Module 01 computer forensics in todays worldModule 01 computer forensics in todays world
Module 01 computer forensics in todays world
 
Virtualisation with v mware
Virtualisation with v mwareVirtualisation with v mware
Virtualisation with v mware
 
Virtualisation overview
Virtualisation overviewVirtualisation overview
Virtualisation overview
 
Virtualisation basics
Virtualisation basicsVirtualisation basics
Virtualisation basics
 
Introduction to virtualisation
Introduction to virtualisationIntroduction to virtualisation
Introduction to virtualisation
 
6 service operation
6 service operation6 service operation
6 service operation
 
5 service transition
5 service transition5 service transition
5 service transition
 
4 service design
4 service design4 service design
4 service design
 
3 service strategy
3 service strategy3 service strategy
3 service strategy
 
2 the service lifecycle
2 the service lifecycle2 the service lifecycle
2 the service lifecycle
 
1 introduction to itil v[1].3
1 introduction to itil v[1].31 introduction to itil v[1].3
1 introduction to itil v[1].3
 
Visual studio 2008 overview
Visual studio 2008 overviewVisual studio 2008 overview
Visual studio 2008 overview
 
Vb introduction.
Vb introduction.Vb introduction.
Vb introduction.
 

Kürzlich hochgeladen

IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfJamie (Taka) Wang
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDELiveplex
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemAsko Soukka
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAshyamraj55
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Brian Pichman
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024D Cloud Solutions
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureEric D. Schabell
 

Kürzlich hochgeladen (20)

IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
activity_diagram_combine_v4_20190827.pdfactivity_diagram_combine_v4_20190827.pdf
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDEADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
ADOPTING WEB 3 FOR YOUR BUSINESS: A STEP-BY-STEP GUIDE
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
Bird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystemBird eye's view on Camunda open source ecosystem
Bird eye's view on Camunda open source ecosystem
 
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPAAnypoint Code Builder , Google Pub sub connector and MuleSoft RPA
Anypoint Code Builder , Google Pub sub connector and MuleSoft RPA
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
20230104 - machine vision
20230104 - machine vision20230104 - machine vision
20230104 - machine vision
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )Building Your Own AI Instance (TBLC AI )
Building Your Own AI Instance (TBLC AI )
 
Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024Artificial Intelligence & SEO Trends for 2024
Artificial Intelligence & SEO Trends for 2024
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
OpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability AdventureOpenShift Commons Paris - Choose Your Own Observability Adventure
OpenShift Commons Paris - Choose Your Own Observability Adventure
 

Rubyforjavaprogrammers 1210167973516759-9

Hinweis der Redaktion

  1. Sign language analogy New concepts new culture/idioms Become a better programmer in all languages
  2. Coming from a Java background, Ruby offers many new concepts Ruby has become very popular with Java people so there are lots of people to help you get through the initial learning curve It’s a “hot” technology It can be run on existing J2EE infrastructure
  3. Influenced by many other languages
  4. A lot of confusion around terminology Let’s start with definitions
  5. the java example will result in a compile error The perl example will automagically convert the string to an int
  6. The java sample will fail at compile time if the Foo class does not contain a getUser() method The smalltalk sample will wait until the getuser message is sent to the object before seeing if there is a method
  7. Ruby classes are first class objects, java classes are not Ruby class methods are methods on a real object (can be overridden etc) Java static methods are functions scoped to a Class name Ruby this will be null when executing a static method Everything in Ruby is an object
  8. Inheritance is &lt; Enforced naming - Constants start with capital, variable with lower - @ for instance, @@ for class Naming by convention - Methods: all lowercase with underscores - Variables: camel case Others - Scope is private, protected, public. Default scope is public - attr_accessor generates zebras() and zebras=() - default values Object construction - new is a method on the class - is not required to return an instance of this class - initialize is the second stage of object creation Self is the equivalent of this except that it always has a value
  9. Methods that return a boolean will end in “?”
  10. Methods that return a boolean will end in “?”
  11. Methods that return a boolean will end in “?”
  12. Methods that return a boolean will end in “?”
  13. Methods that return a boolean will end in “?”
  14. Bang means the method is dangerous in some way Often this means that it modifies the receiver but not always This is convention only - not mandated by the compiler
  15. To create a new list with two strings we do it in three separate steps
  16. Special case where the hash is the last parameter to a method :symbol notation
  17. Java requires double escaping because it’s a string Requires two explicit temporary objects
  18. ActiveRecord::Base uses method_missing to convert the first method into the second
  19. method_missing can be used to create a proxy object Problem: Object has quite a few methods already so you can’t proxy those
  20. Works really well for new methods Methods already defined in Object don’t get passed to method_missing
  21. Works really well for new methods Methods already defined in Object don’t get passed to method_missing
  22. We can override the methods in Object and have them call method_missing
  23. Problem: Object implements a lot of methods method_missing only gets called when there isn’t a method by that name
  24. doesn’t work for to_s as that method was inherited from Kernel This removes all methods (except __send__ and __id__) from the instance
  25. In java, we care what the type is In Ruby, we don’t All we care about is the fact that it responds to &lt;&lt;
  26. Since objects are so malleable in ruby, it makes less sense to care about the exact class of an object We care about the behaviour (or interface) This allows us to do interesting things like quietly changing the return type of an object
  27. Let’s look at an example
  28. In Java, integers will quietly overflow and wrap around to negative numbers Problem: Java does not throw an exception during overflow conditions Problem: Overflow is possible at all
  29. In Java, integers will quietly overflow and wrap around to negative numbers Problem: Java does not throw an exception during overflow conditions Problem: Overflow is possible at all
  30. The * method will return Fixnum’s until the number is too big to fit inside a Fixnum It will then return Bignum Bignums are slower but are able to handle much larger values Wouldn’t be possible without duck typing
  31. The method ‘lambda’ returns a Proc instance
  32. The method ‘lambda’ returns a Proc instance
  33. The method ‘lambda’ returns a Proc instance
  34. The method ‘lambda’ returns a Proc instance
  35. The block will get passed into the method
  36. Idiom: Use curlies for single line blocks and do/end for multiple line blocks Difference in precedance
  37. Some size difference due to optional syntax Most due to use of closures
  38. Open file for writing begin/rescue == try/finally
  39. All the business logic is inside the closure
  40. Sort takes a closure foreach takes one File.open takes one
  41. The closest thing Java has to closures are anonymous inner classes. The inner class has access to final local variables as well as instance and static variables (final or not) from the enclosing class One of the characteristics of proper closures is that they are syntactically clean. These are not.
  42. There have been several rounds of proposals for this It’s not clear if they’ll ever be added to Java
  43. C++ allows multiple inheritance Issues when the same method is declared in multiple branches
  44. No issues with inheriting an interface twice as no methods are implemented in the interface
  45. Mixin is a collection of methods that are grouped together A class can include as many mixins as it wants Mixins can work together with existing methods - ie Enumerable
  46. Create class Define method
  47. Reopen class Add second method Now Foo has two methods
  48. This time we’re replacing a method
  49. This is something that Java would never allow
  50. Since we use late binding, we can manipulate
  51. Create classes Add/modify/remove methods Rename methods
  52. C++ would expand this using a pre-processor Ruby adds new methods at run time
  53. ActiveRecord uses meta programming to establish relationships between model objects acts_as_* methods modify multiple classes and can make significant change to the behaviour
  54. Much more complicated example One of the more interesting methods in the Ruby source Takes a method and ensures that after it’s been called once, the result is cached See my slides from the TSOT talk
  55. Allows you to walk through all “live” objects in the heap
  56. Allows you to walk through all “live” objects in the heap
  57. You may never use these directly but the fact that the language supports them means that frameworks can be built that you can use
  58. 1.9 - Faster - Somewhat incompatible Parrot - Common runtime for perl and python and other dynamic languages - Name came from a 2001 april fools joke Definitions DLR = Dynamic Language Runtime (sits on top of CLR) CLR = Common Language Runtime (runtime for .NET)
  59. 1.9 - Faster - Somewhat incompatible Parrot - Common runtime for perl and python and other dynamic languages - Name came from a 2001 april fools joke Definitions DLR = Dynamic Language Runtime (sits on top of CLR) CLR = Common Language Runtime (runtime for .NET)
  60. Lots of startups and ...