SlideShare uma empresa Scribd logo
1 de 104
Ruby for Java Programmers ,[object Object],[object Object]
Why learn another language?
Why Ruby?
Timeline: 1993 to 2000 ,[object Object],[object Object],[object Object]
Timeline: 2000-2004 ,[object Object],[object Object]
Timeline: 2004-today ,[object Object],[object Object]
What influenced it?
Terminology ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Defining strong/weak typing ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Early/late binding ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Similarities ,[object Object],[object Object],[object Object],[object Object]
Differences ,[object Object],Java string = String.valueOf(1); Ruby string = 1.to_s() Primitive Object
Differences ,[object Object],throw  new IllegalArgumentException( "oops" ); raise  TypeError.new( "oops" ) Keywords Methods
Differences ,[object Object],[object Object],puts( "foo" ); puts  "foo" Idiomatic (better) style
Differences ,[object Object],[object Object],[object Object]
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 unless if  name. nil ? do_something end do_something  if  name. nil ? unless  name. nil ? do_something end do_something  unless  name. nil ?
Dangerous methods name =  &quot;   foo   &quot; name.strip name.strip! Returns a new string. Doesn’t modify name. Modifies name  and returns that. Dangerous!
Philosophy ,[object Object],[object Object],[object Object],[object Object]
Initializing arrays List<String> list =  new  ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; );
Same only ruby List<String> list =  new  ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; ); list = Array.new list <<  'foo' list <<  'bar'
[] List<String> list =  new  ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; ); list = Array.new list <<  'foo' list <<  'bar' list = [ 'foo' ,  'bar' ]
%w() List<String> list =  new  ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; ); 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( &quot;foo&quot; ); list.add( &quot;bar&quot; ); List<String> list = Arrays.asList( &quot;foo&quot; ,  &quot;bar&quot; ); 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( &quot;foo&quot; ,  &quot;one&quot; ); map.put( &quot;bar&quot; ,  &quot;two&quot; ); 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( &quot;^s*(.+)s*$&quot; ); Matcher matcher =  pattern .matcher(line); if ( matcher.matches() ) { doSomething(); }
Regular Expressions Pattern pattern = Pattern.compile( &quot;^s*(.+)s*$&quot; ); Matcher matcher =  pattern .matcher(line); if ( matcher.matches() ) { doSomething(); } do_something  if  line =~  /^*(.+)*$/
Nil and Null Java’s null Ruby’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 &quot;main&quot; java.lang.NullPointerException nil.get_user ->  NoMethodError: undefined method ‘get_user’ for nil:NilClass
Implications of late binding ,[object Object],[object Object]
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  => [  &quot;name = ?&quot; , name])
Creating proxy objects ,[object Object],[object Object],[object Object]
Implementing a proxy class  Proxy def  method_missing name, *args, &proc puts name,args end end
Implementing a proxy class  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  p rivate_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 ,[object Object],[object Object],[object Object],[object Object],[object Object]
Types public   void  foo( ArrayList list ) { list.add( &quot;foo&quot; ); } 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 ,[object Object],[object Object]
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( &quot;  a=&quot; +a); System. out .println( &quot;a+1=&quot; +(a+1)); a=2147483647 a+1= ??
Overflow conditions int  a = Integer. MAX_VALUE ; System. out .println( &quot;  a=&quot; +a); System. out .println( &quot;a+1=&quot; +(a+1)); a=2147483647 a+1=-2147483648 oops
Overflow in ruby? number =  1000 1 .upto( 4 )  do puts  &quot;#{number.class} #{number}&quot; number = number * number end Fixnum 1000 Fixnum 1000000 Bignum 1000000000000 Bignum 1000000000000000000000000
Closures ,[object Object]
Closures ,[object Object],[object Object],[object Object],[object Object],[object Object]
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? ,[object Object],[object Object]
// Read the lines and split them into columns List<String[]> lines=  new  ArrayList<String[]>(); BufferedReader reader =  null ; try  { reader =  new  BufferedReader( new  FileReader( &quot;people.txt&quot; )); String line = reader.readLine(); while ( line !=  null  ) { lines.add( line.split( &quot;&quot; ) ); } } 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( &quot;people.txt&quot; ) ); for ( String[] strings : lines ) { StringBuilder builder =  new  StringBuilder(); for (  int  i=0; i<strings. length ; i++ ) { if ( i != 0 ) { builder.append( &quot;&quot; ); } 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( &quot;&quot; ) 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( &quot;&quot; ) 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? ,[object Object],[object Object],[object Object],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 ,[object Object],[object Object],[object Object]
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 ,[object Object],[object Object],[object Object],[object Object]
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 classes class  String def  one puts  'one' end end We reopened  a CORE class and modified it
Metaprogramming ,[object Object],[object Object]
What changes can we make at runtime? ,[object Object],[object Object]
attr_accessor class  Foo attr_accessor  :bar end class  Foo def  bar @bar end def  bar=(newBar) @bar  = newBar end end Getter Setter
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 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 “ Here Doc” Evaluates to  String
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 String substitution
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 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 <<-&quot; end ;&quot;, __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? ,[object Object],[object Object],[object Object]
Downsides ,[object Object],[object Object]
Implementations ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Implementations ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
JRuby ,[object Object],[object Object],[object Object],[object Object],[object Object]
Ruby on Rails ,[object Object],[object Object],[object Object]
Who’s using rails? ,[object Object]
JRuby on Rails? ,[object Object],[object Object],[object Object],[object Object],[object Object]
Recap ,[object Object],[object Object],[object Object]
Recap ,[object Object],[object Object],[object Object],[object Object]
Contacting me ,[object Object],[object Object]

Mais conteúdo relacionado

Mais procurados

Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentationadamcookeuk
 
Ruby Programming Introduction
Ruby Programming IntroductionRuby Programming Introduction
Ruby Programming IntroductionAnthony Brown
 
Ruby An Introduction
Ruby An IntroductionRuby An Introduction
Ruby An IntroductionShrinivasan T
 
Ruby and Rails by example
Ruby and Rails by exampleRuby and Rails by example
Ruby and Rails by examplebryanbibat
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the BasicsMichael Koby
 
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 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.pptcallroom
 
name name2 n2
name name2 n2name name2 n2
name name2 n2callroom
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueJames Thompson
 

Mais procurados (13)

Ruby
RubyRuby
Ruby
 
Ruby on Rails Presentation
Ruby on Rails PresentationRuby on Rails Presentation
Ruby on Rails Presentation
 
Ruby Programming Introduction
Ruby Programming IntroductionRuby Programming Introduction
Ruby Programming Introduction
 
Ruby An Introduction
Ruby An IntroductionRuby An Introduction
Ruby An Introduction
 
Ruby and Rails by example
Ruby and Rails by exampleRuby and Rails by example
Ruby and Rails by example
 
Ruby: Beyond the Basics
Ruby: Beyond the BasicsRuby: Beyond the Basics
Ruby: Beyond the Basics
 
Ruby for Perl Programmers
Ruby for Perl ProgrammersRuby for Perl Programmers
Ruby for Perl Programmers
 
name name2 n
name name2 nname name2 n
name name2 n
 
ppt18
ppt18ppt18
ppt18
 
name name2 n2.ppt
name name2 n2.pptname name2 n2.ppt
name name2 n2.ppt
 
ppt9
ppt9ppt9
ppt9
 
name name2 n2
name name2 n2name name2 n2
name name2 n2
 
Learn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a RescueLearn Ruby 2011 - Session 5 - Looking for a Rescue
Learn Ruby 2011 - Session 5 - Looking for a Rescue
 

Destaque

Ruby vs Java
Ruby vs JavaRuby vs Java
Ruby vs JavaBelighted
 
MacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meetMacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meetMatt Aimonetti
 
Getting Started with Android Development
Getting Started with Android DevelopmentGetting Started with Android Development
Getting Started with Android DevelopmentEdureka!
 
«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»Olga Lavrentieva
 
Criação de uma equipe de QAs, do Waterfall ao Agile
Criação de uma equipe de QAs, do Waterfall ao AgileCriação de uma equipe de QAs, do Waterfall ao Agile
Criação de uma equipe de QAs, do Waterfall ao AgileRobson Agapito Correa
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over ClassesAman King
 
Ruby's Object Model: Metaprogramming and other Magic
Ruby's Object Model: Metaprogramming and other MagicRuby's Object Model: Metaprogramming and other Magic
Ruby's Object Model: Metaprogramming and other MagicBurke Libbey
 
QA Automation Battle: Java vs Python vs Ruby [09.04.2015]
QA Automation Battle: Java vs Python vs Ruby [09.04.2015]QA Automation Battle: Java vs Python vs Ruby [09.04.2015]
QA Automation Battle: Java vs Python vs Ruby [09.04.2015]GoIT
 
Continuous Delivery in Ruby
Continuous Delivery in RubyContinuous Delivery in Ruby
Continuous Delivery in RubyBrian Guthrie
 
Jruby, o melhor de 2 mundos (MacGyver + ChuckNorris)
Jruby, o melhor de 2 mundos (MacGyver + ChuckNorris)Jruby, o melhor de 2 mundos (MacGyver + ChuckNorris)
Jruby, o melhor de 2 mundos (MacGyver + ChuckNorris)Marcio Sfalsin
 
From One to Many: Evolving VPC Design (ARC401) | AWS re:Invent 2013
From One to Many:  Evolving VPC Design (ARC401) | AWS re:Invent 2013From One to Many:  Evolving VPC Design (ARC401) | AWS re:Invent 2013
From One to Many: Evolving VPC Design (ARC401) | AWS re:Invent 2013Amazon Web Services
 
CIS13: Bootcamp: Ping Identity OAuth and OpenID Connect In Action with PingFe...
CIS13: Bootcamp: Ping Identity OAuth and OpenID Connect In Action with PingFe...CIS13: Bootcamp: Ping Identity OAuth and OpenID Connect In Action with PingFe...
CIS13: Bootcamp: Ping Identity OAuth and OpenID Connect In Action with PingFe...CloudIDSummit
 

Destaque (20)

Ruby vs Java
Ruby vs JavaRuby vs Java
Ruby vs Java
 
Ruby everywhere
Ruby everywhereRuby everywhere
Ruby everywhere
 
Scala vs Ruby
Scala vs RubyScala vs Ruby
Scala vs Ruby
 
Java vs. Ruby
Java vs. RubyJava vs. Ruby
Java vs. Ruby
 
MacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meetMacRuby - When objective-c and Ruby meet
MacRuby - When objective-c and Ruby meet
 
Getting Started with Android Development
Getting Started with Android DevelopmentGetting Started with Android Development
Getting Started with Android Development
 
Ruby 1.9
Ruby 1.9Ruby 1.9
Ruby 1.9
 
«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»«Работа с базами данных с использованием Sequel»
«Работа с базами данных с использованием Sequel»
 
Seu site voando
Seu site voandoSeu site voando
Seu site voando
 
Apresentação sobre JRuby
Apresentação sobre JRubyApresentação sobre JRuby
Apresentação sobre JRuby
 
Beginner's Sinatra
Beginner's SinatraBeginner's Sinatra
Beginner's Sinatra
 
Criação de uma equipe de QAs, do Waterfall ao Agile
Criação de uma equipe de QAs, do Waterfall ao AgileCriação de uma equipe de QAs, do Waterfall ao Agile
Criação de uma equipe de QAs, do Waterfall ao Agile
 
Ruby OOP: Objects over Classes
Ruby OOP: Objects over ClassesRuby OOP: Objects over Classes
Ruby OOP: Objects over Classes
 
Ruby's Object Model: Metaprogramming and other Magic
Ruby's Object Model: Metaprogramming and other MagicRuby's Object Model: Metaprogramming and other Magic
Ruby's Object Model: Metaprogramming and other Magic
 
QA Automation Battle: Java vs Python vs Ruby [09.04.2015]
QA Automation Battle: Java vs Python vs Ruby [09.04.2015]QA Automation Battle: Java vs Python vs Ruby [09.04.2015]
QA Automation Battle: Java vs Python vs Ruby [09.04.2015]
 
Continuous Delivery in Ruby
Continuous Delivery in RubyContinuous Delivery in Ruby
Continuous Delivery in Ruby
 
Jruby, o melhor de 2 mundos (MacGyver + ChuckNorris)
Jruby, o melhor de 2 mundos (MacGyver + ChuckNorris)Jruby, o melhor de 2 mundos (MacGyver + ChuckNorris)
Jruby, o melhor de 2 mundos (MacGyver + ChuckNorris)
 
From One to Many: Evolving VPC Design (ARC401) | AWS re:Invent 2013
From One to Many:  Evolving VPC Design (ARC401) | AWS re:Invent 2013From One to Many:  Evolving VPC Design (ARC401) | AWS re:Invent 2013
From One to Many: Evolving VPC Design (ARC401) | AWS re:Invent 2013
 
CIS13: Bootcamp: Ping Identity OAuth and OpenID Connect In Action with PingFe...
CIS13: Bootcamp: Ping Identity OAuth and OpenID Connect In Action with PingFe...CIS13: Bootcamp: Ping Identity OAuth and OpenID Connect In Action with PingFe...
CIS13: Bootcamp: Ping Identity OAuth and OpenID Connect In Action with PingFe...
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 

Semelhante a Ruby For Java Programmers

Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9sagaroceanic11
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Languagezone
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de JavascriptBernard Loire
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Parkpointstechgeeks
 
Jerry Shea Resume And Addendum 5 2 09
Jerry  Shea Resume And Addendum 5 2 09Jerry  Shea Resume And Addendum 5 2 09
Jerry Shea Resume And Addendum 5 2 09gshea11
 
Majlis Persaraan Pn.Hjh.Normah bersama guru-guru Sesi Petang
Majlis Persaraan Pn.Hjh.Normah bersama guru-guru Sesi PetangMajlis Persaraan Pn.Hjh.Normah bersama guru-guru Sesi Petang
Majlis Persaraan Pn.Hjh.Normah bersama guru-guru Sesi PetangImsamad
 
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
 
name name2 n
name name2 nname name2 n
name name2 ncallroom
 

Semelhante a Ruby For Java Programmers (20)

Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9Rubyforjavaprogrammers 1210167973516759-9
Rubyforjavaprogrammers 1210167973516759-9
 
Javascript
JavascriptJavascript
Javascript
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Javascript
JavascriptJavascript
Javascript
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
 
Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Park
 
MMBJ Shanzhai Culture
MMBJ Shanzhai CultureMMBJ Shanzhai Culture
MMBJ Shanzhai Culture
 
Jerry Shea Resume And Addendum 5 2 09
Jerry  Shea Resume And Addendum 5 2 09Jerry  Shea Resume And Addendum 5 2 09
Jerry Shea Resume And Addendum 5 2 09
 
Majlis Persaraan Pn.Hjh.Normah bersama guru-guru Sesi Petang
Majlis Persaraan Pn.Hjh.Normah bersama guru-guru Sesi PetangMajlis Persaraan Pn.Hjh.Normah bersama guru-guru Sesi Petang
Majlis Persaraan Pn.Hjh.Normah bersama guru-guru Sesi Petang
 
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
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
ppt7
ppt7ppt7
ppt7
 
ppt2
ppt2ppt2
ppt2
 
name name2 n
name name2 nname name2 n
name name2 n
 

Mais de Mike Bowler

Retrospective Magic - Toronto Agile Conference
Retrospective Magic - Toronto Agile ConferenceRetrospective Magic - Toronto Agile Conference
Retrospective Magic - Toronto Agile ConferenceMike Bowler
 
Retrospective science
Retrospective scienceRetrospective science
Retrospective scienceMike Bowler
 
Brain Talk: More effective conversations through clean language
Brain Talk: More effective conversations through clean languageBrain Talk: More effective conversations through clean language
Brain Talk: More effective conversations through clean languageMike Bowler
 
Continuous Delivery: Responding to Change Faster Than Ever Before - SDEC14
Continuous Delivery: Responding to Change Faster Than Ever Before - SDEC14Continuous Delivery: Responding to Change Faster Than Ever Before - SDEC14
Continuous Delivery: Responding to Change Faster Than Ever Before - SDEC14Mike Bowler
 
Continuous Delivery for Agile Teams
Continuous Delivery for Agile TeamsContinuous Delivery for Agile Teams
Continuous Delivery for Agile TeamsMike Bowler
 
Inside Enumerable
Inside EnumerableInside Enumerable
Inside EnumerableMike Bowler
 
Exploring the magic behind dynamic finders: diving into ActiveRecord::Base.me...
Exploring the magic behind dynamic finders: diving into ActiveRecord::Base.me...Exploring the magic behind dynamic finders: diving into ActiveRecord::Base.me...
Exploring the magic behind dynamic finders: diving into ActiveRecord::Base.me...Mike Bowler
 

Mais de Mike Bowler (8)

Retrospective Magic - Toronto Agile Conference
Retrospective Magic - Toronto Agile ConferenceRetrospective Magic - Toronto Agile Conference
Retrospective Magic - Toronto Agile Conference
 
Retrospective science
Retrospective scienceRetrospective science
Retrospective science
 
Brain Talk: More effective conversations through clean language
Brain Talk: More effective conversations through clean languageBrain Talk: More effective conversations through clean language
Brain Talk: More effective conversations through clean language
 
Continuous Delivery: Responding to Change Faster Than Ever Before - SDEC14
Continuous Delivery: Responding to Change Faster Than Ever Before - SDEC14Continuous Delivery: Responding to Change Faster Than Ever Before - SDEC14
Continuous Delivery: Responding to Change Faster Than Ever Before - SDEC14
 
Continuous Delivery for Agile Teams
Continuous Delivery for Agile TeamsContinuous Delivery for Agile Teams
Continuous Delivery for Agile Teams
 
Inside Enumerable
Inside EnumerableInside Enumerable
Inside Enumerable
 
Exploring the magic behind dynamic finders: diving into ActiveRecord::Base.me...
Exploring the magic behind dynamic finders: diving into ActiveRecord::Base.me...Exploring the magic behind dynamic finders: diving into ActiveRecord::Base.me...
Exploring the magic behind dynamic finders: diving into ActiveRecord::Base.me...
 
Date Once
Date OnceDate Once
Date Once
 

Último

Marketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent ChirchirMarketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent Chirchirictsugar
 
Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMVoces Mineras
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxMarkAnthonyAurellano
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesKeppelCorporation
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCRashishs7044
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607dollysharma2066
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCRashishs7044
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdfKhaled Al Awadi
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfrichard876048
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...ictsugar
 
IoT Insurance Observatory: summary 2024
IoT Insurance Observatory:  summary 2024IoT Insurance Observatory:  summary 2024
IoT Insurance Observatory: summary 2024Matteo Carbone
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfJos Voskuil
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy Verified Accounts
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfpollardmorgan
 
India Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportIndia Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportMintel Group
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Servicecallgirls2057
 
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckPitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckHajeJanKamps
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607dollysharma2066
 

Último (20)

Marketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent ChirchirMarketplace and Quality Assurance Presentation - Vincent Chirchir
Marketplace and Quality Assurance Presentation - Vincent Chirchir
 
Memorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQMMemorándum de Entendimiento (MoU) entre Codelco y SQM
Memorándum de Entendimiento (MoU) entre Codelco y SQM
 
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptxContemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
Contemporary Economic Issues Facing the Filipino Entrepreneur (1).pptx
 
Annual General Meeting Presentation Slides
Annual General Meeting Presentation SlidesAnnual General Meeting Presentation Slides
Annual General Meeting Presentation Slides
 
8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR8447779800, Low rate Call girls in Saket Delhi NCR
8447779800, Low rate Call girls in Saket Delhi NCR
 
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
(Best) ENJOY Call Girls in Faridabad Ex | 8377087607
 
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR8447779800, Low rate Call girls in Tughlakabad Delhi NCR
8447779800, Low rate Call girls in Tughlakabad Delhi NCR
 
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdfNewBase  19 April  2024  Energy News issue - 1717 by Khaled Al Awadi.pdf
NewBase 19 April 2024 Energy News issue - 1717 by Khaled Al Awadi.pdf
 
Innovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdfInnovation Conference 5th March 2024.pdf
Innovation Conference 5th March 2024.pdf
 
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...Global Scenario On Sustainable  and Resilient Coconut Industry by Dr. Jelfina...
Global Scenario On Sustainable and Resilient Coconut Industry by Dr. Jelfina...
 
Corporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information TechnologyCorporate Profile 47Billion Information Technology
Corporate Profile 47Billion Information Technology
 
IoT Insurance Observatory: summary 2024
IoT Insurance Observatory:  summary 2024IoT Insurance Observatory:  summary 2024
IoT Insurance Observatory: summary 2024
 
Digital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdfDigital Transformation in the PLM domain - distrib.pdf
Digital Transformation in the PLM domain - distrib.pdf
 
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCREnjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
Enjoy ➥8448380779▻ Call Girls In Sector 18 Noida Escorts Delhi NCR
 
Buy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail AccountsBuy gmail accounts.pdf Buy Old Gmail Accounts
Buy gmail accounts.pdf Buy Old Gmail Accounts
 
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdfIntro to BCG's Carbon Emissions Benchmark_vF.pdf
Intro to BCG's Carbon Emissions Benchmark_vF.pdf
 
India Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample ReportIndia Consumer 2024 Redacted Sample Report
India Consumer 2024 Redacted Sample Report
 
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort ServiceCall US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
Call US-88OO1O2216 Call Girls In Mahipalpur Female Escort Service
 
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deckPitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
Pitch Deck Teardown: Geodesic.Life's $500k Pre-seed deck
 
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607FULL ENJOY Call girls in Paharganj Delhi | 8377087607
FULL ENJOY Call girls in Paharganj Delhi | 8377087607
 

Ruby For Java Programmers

  • 1.
  • 2. Why learn another language?
  • 4.
  • 5.
  • 6.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16. 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
  • 17. Multiline if if name. nil ? do_something end
  • 18. Multiline if if name. nil ? do_something end Notice the question mark
  • 19. With an else if name. nil ? do_something else something_else end
  • 20. Single line if if name. nil ? do_something end do_something if name. nil ?
  • 21. Both kinds of unless if name. nil ? do_something end do_something if name. nil ? unless name. nil ? do_something end do_something unless name. nil ?
  • 22. Dangerous methods name = &quot; foo &quot; name.strip name.strip! Returns a new string. Doesn’t modify name. Modifies name and returns that. Dangerous!
  • 23.
  • 24. Initializing arrays List<String> list = new ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; );
  • 25. Same only ruby List<String> list = new ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; ); list = Array.new list << 'foo' list << 'bar'
  • 26. [] List<String> list = new ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; ); list = Array.new list << 'foo' list << 'bar' list = [ 'foo' , 'bar' ]
  • 27. %w() List<String> list = new ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; ); list = Array.new list << 'foo' list << 'bar' list = [ 'foo' , 'bar' ] list = %w(foo bar)
  • 28. In fairness to java... List<String> list = new ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; ); List<String> list = Arrays.asList( &quot;foo&quot; , &quot;bar&quot; ); list = Array.new list << 'foo' list << 'bar' list = [ 'foo' , 'bar' ] list = %w(foo bar)
  • 29. Same idea with hashes Map<String,String> map = new HashMap<String,String>(); map.put( &quot;foo&quot; , &quot;one&quot; ); map.put( &quot;bar&quot; , &quot;two&quot; ); map = { 'foo' => 'one' , 'bar' => 'two' }
  • 30. Special case for Hash hash = { :a => 5 , :b => 3 } do_stuff 30 , hash do_stuff 100 , :a => 5 , :b => 3
  • 31. Regular Expressions Pattern pattern = Pattern.compile( &quot;^s*(.+)s*$&quot; ); Matcher matcher = pattern .matcher(line); if ( matcher.matches() ) { doSomething(); }
  • 32. Regular Expressions Pattern pattern = Pattern.compile( &quot;^s*(.+)s*$&quot; ); Matcher matcher = pattern .matcher(line); if ( matcher.matches() ) { doSomething(); } do_something if line =~ /^*(.+)*$/
  • 33. Nil and Null Java’s null Ruby’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 &quot;main&quot; java.lang.NullPointerException nil.get_user -> NoMethodError: undefined method ‘get_user’ for nil:NilClass
  • 34.
  • 36. What if there isn’t a method for the specified message?
  • 37. method_missing example from ActiveRecord user = Users.find_by_name(name) user = Users.find( :first , :conditions => [ &quot;name = ?&quot; , name])
  • 38.
  • 39. Implementing a proxy class Proxy def method_missing name, *args, &proc puts name,args end end
  • 40. Implementing a proxy class 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
  • 41. Overriding to_s class Proxy def method_missing name, *args, &proc puts name,args end def to_s method_missing :to_s, [] end end
  • 42. = • === • =~ • __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 p rivate_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
  • 43. 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
  • 44. Unix was not designed to stop people from doing stupid things, because that would also stop them from doing clever things. — Doug Gwyn
  • 45.
  • 46. Types public void foo( ArrayList list ) { list.add( &quot;foo&quot; ); } def foo list list << 'foo' end What’s the type? What’s the type?
  • 47. 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
  • 48.
  • 49. How does this change how we think of types? think of types? think of types?
  • 50. Overflow conditions int a = Integer. MAX_VALUE ; System. out .println( &quot; a=&quot; +a); System. out .println( &quot;a+1=&quot; +(a+1)); a=2147483647 a+1= ??
  • 51. Overflow conditions int a = Integer. MAX_VALUE ; System. out .println( &quot; a=&quot; +a); System. out .println( &quot;a+1=&quot; +(a+1)); a=2147483647 a+1=-2147483648 oops
  • 52. Overflow in ruby? number = 1000 1 .upto( 4 ) do puts &quot;#{number.class} #{number}&quot; number = number * number end Fixnum 1000 Fixnum 1000000 Bignum 1000000000000 Bignum 1000000000000000000000000
  • 53.
  • 54.
  • 55. Closures multiplier = 5 block = lambda {|number| puts number * multiplier } A block An instance of Proc lambda() is a method to convert blocks into Procs
  • 56. Closures multiplier = 5 block = lambda {|number| puts number * multiplier } Parameter to the block
  • 57. Closures multiplier = 5 block = lambda {|number| puts number * multiplier } Able to access variables from outside the block
  • 58. 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
  • 59. 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
  • 60. Alternate syntax multiplier = 5 1.upto(3) {|number| puts number * multiplier } 1.upto(3) do |number| puts number * multiplier end Equivalent
  • 61.
  • 62. // Read the lines and split them into columns List<String[]> lines= new ArrayList<String[]>(); BufferedReader reader = null ; try { reader = new BufferedReader( new FileReader( &quot;people.txt&quot; )); String line = reader.readLine(); while ( line != null ) { lines.add( line.split( &quot;&quot; ) ); } } 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( &quot;people.txt&quot; ) ); for ( String[] strings : lines ) { StringBuilder builder = new StringBuilder(); for ( int i=0; i<strings. length ; i++ ) { if ( i != 0 ) { builder.append( &quot;&quot; ); } 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( &quot;&quot; ) end end
  • 63. Closure File Example file = File. new (fileName, 'w' ) begin file.puts ‘some content’ rescue file.close end
  • 64. Closure File Example file = File. new (fileName, 'w' ) begin file.puts ‘some content’ rescue file.close end Only one line of business logic
  • 65. 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
  • 66. 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( &quot;&quot; ) end end
  • 67. 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
  • 68.
  • 69.
  • 70. C++ : multiple inheritance
  • 73. Mixins Cannot be instantiated Can be mixed in
  • 74. 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
  • 75. 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
  • 76.
  • 77. Reopening classes class Foo def one puts 'one' end end
  • 78. Reopening classes class Foo def one puts 'one' end end class Foo def two puts 'two' end end Reopening the same class
  • 79. Reopening classes class Foo def one puts 'one' end end class Foo def one puts '1' end end Replacing, not adding a method
  • 80. Reopening core classes class String def one puts 'one' end end We reopened a CORE class and modified it
  • 81.
  • 82.
  • 83. attr_accessor class Foo attr_accessor :bar end class Foo def bar @bar end def bar=(newBar) @bar = newBar end end Getter Setter
  • 84. 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
  • 85. 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 “ Here Doc” Evaluates to String
  • 86. 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 String substitution
  • 87. 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 Executes the string in the context of the class
  • 88. Result class Foo def bar @bar end def bar=(newBar) @bar = newBar end end
  • 89. ActiveRecord class ListItem < ActiveRecord::Base belongs_to :amazon_item acts_as_taggable acts_as_list :scope => :user end
  • 90. Date :: once def once(*ids) # :nodoc: for id in ids module_eval <<-&quot; end ;&quot;, __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
  • 91. ObjectSpace ObjectSpace.each_object do |o| puts o end ObjectSpace.each_object(String) do |o| puts o end
  • 92. ObjectSpace ObjectSpace.each_object do |o| puts o end ObjectSpace.each_object(String) do |o| puts o end All objects Only Strings
  • 93. Continuations A snapshot of the call stack that the application can revert to at some point in the future
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.