Se ha denunciado esta presentación.
Utilizamos tu perfil de LinkedIn y tus datos de actividad para personalizar los anuncios y mostrarte publicidad más relevante. Puedes cambiar tus preferencias de publicidad en cualquier momento.

Ruby For Java Programmers

14.519 visualizaciones

Publicado el

One of the advantages of learning a new language is being exposed to new idioms and new approaches to solving old problems. In this talk, we will introduce the Ruby language with particular focus on the idioms and concepts that are different from what is found in Java.

We will introduce concepts such as closures, continuations and meta programming. We will also examine powerful techniques that are practically impossible in Java due to its compile time binding of types.

No experience with Ruby is assumed although an understanding of Java would be helpful.

This talk was given at the Toronto Java Users Group in April 2008

Publicado en: Empresariales, Tecnología
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí
  • Follow the link, new dating source: ❶❶❶ http://bit.ly/36cXjBY ❶❶❶
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí
  • Sex in your area is here: ❤❤❤ http://bit.ly/36cXjBY ❤❤❤
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí
  • DOWNLOAD THIS BOOKS INTO AVAILABLE FORMAT (2019 Update) ......................................................................................................................... ......................................................................................................................... Download Full PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download Full EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download Full doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download PDF EBOOK here { https://soo.gd/irt2 } ......................................................................................................................... Download EPUB Ebook here { https://soo.gd/irt2 } ......................................................................................................................... Download doc Ebook here { https://soo.gd/irt2 } ......................................................................................................................... ......................................................................................................................... ................................................................................................................................... eBook is an electronic version of a traditional print book THIS can be read by using a personal computer or by using an eBook reader. (An eBook reader can be a software application for use on a computer such as Microsoft's free Reader application, or a book-sized computer THIS is used solely as a reading device such as Nuvomedia's Rocket eBook.) Users can purchase an eBook on diskette or CD, but the most popular method of getting an eBook is to purchase a downloadable file of the eBook (or other reading material) from a Web site (such as Barnes and Noble) to be read from the user's computer or reading device. Generally, an eBook can be downloaded in five minutes or less ......................................................................................................................... .............. Browse by Genre Available eBooks .............................................................................................................................. Art, Biography, Business, Chick Lit, Children's, Christian, Classics, Comics, Contemporary, Cookbooks, Manga, Memoir, Music, Mystery, Non Fiction, Paranormal, Philosophy, Poetry, Psychology, Religion, Romance, Science, Science Fiction, Self Help, Suspense, Spirituality, Sports, Thriller, Travel, Young Adult, Crime, Ebooks, Fantasy, Fiction, Graphic Novels, Historical Fiction, History, Horror, Humor And Comedy, ......................................................................................................................... ......................................................................................................................... .....BEST SELLER FOR EBOOK RECOMMEND............................................................. ......................................................................................................................... Blowout: Corrupted Democracy, Rogue State Russia, and the Richest, Most Destructive Industry on Earth,-- The Ride of a Lifetime: Lessons Learned from 15 Years as CEO of the Walt Disney Company,-- Call Sign Chaos: Learning to Lead,-- StrengthsFinder 2.0,-- Stillness Is the Key,-- She Said: Breaking the Sexual Harassment Story THIS Helped Ignite a Movement,-- Atomic Habits: An Easy & Proven Way to Build Good Habits & Break Bad Ones,-- Everything Is Figureoutable,-- What It Takes: Lessons in the Pursuit of Excellence,-- Rich Dad Poor Dad: What the Rich Teach Their Kids About Money THIS the Poor and Middle Class Do Not!,-- The Total Money Makeover: Classic Edition: A Proven Plan for Financial Fitness,-- Shut Up and Listen!: Hard Business Truths THIS Will Help You Succeed, ......................................................................................................................... .........................................................................................................................
       Responder 
    ¿Estás seguro?    No
    Tu mensaje aparecerá aquí

Ruby For Java Programmers

  1. 1. Ruby for Java Programmers <ul><li>Mike Bowler </li></ul><ul><li>President, Gargoyle Software Inc. </li></ul>
  2. 2. Why learn another language?
  3. 3. Why Ruby?
  4. 4. Timeline: 1993 to 2000 <ul><li>Created in 1993 by Yukihiro &quot;Matz&quot; Matsumoto </li></ul><ul><li>Ruby was popular in Japan but unknown everywhere else </li></ul><ul><li>All documentation was written in Japanese </li></ul>
  5. 5. Timeline: 2000-2004 <ul><li>First English language book published in 2000 </li></ul><ul><li>A lot of interest in the Agile development community but mostly unknown elsewhere </li></ul>
  6. 6. Timeline: 2004-today <ul><li>The Ruby on Rails framework has pushed ruby into the spotlight </li></ul><ul><li>This is the “killer app” </li></ul>
  7. 7. What influenced it?
  8. 8. Terminology <ul><li>Early </li></ul><ul><li>Late </li></ul><ul><li>Static </li></ul><ul><li>Dynamic </li></ul><ul><li>Strong </li></ul><ul><li>Weak </li></ul>
  9. 9. Defining strong/weak typing <ul><li>Strong typing </li></ul><ul><ul><li>Objects are of a specific type and will not be converted automatically </li></ul></ul><ul><ul><li>Java: “4”/2 results in a compile error </li></ul></ul><ul><li>Weak typing </li></ul><ul><ul><li>Objects can be converted under the covers at any time </li></ul></ul><ul><ul><li>Perl: ‘4’/2 => 2 </li></ul></ul><ul><li>Ruby is strongly typed </li></ul>
  10. 10. Early/late binding <ul><li>Early binding (aka static binding) </li></ul><ul><ul><li>All method invocations must be defined at compile time </li></ul></ul><ul><ul><li>Java: foo.getUser() </li></ul></ul><ul><li>Late binding (aka dynamic binding) </li></ul><ul><ul><li>The runtime does not check that a given method exists until an attempt to invoke it </li></ul></ul><ul><ul><li>Smalltalk: foo user. </li></ul></ul><ul><li>Ruby uses late binding </li></ul>
  11. 11. Similarities <ul><li>Like Java, Ruby... </li></ul><ul><ul><li>runs on a virtual machine </li></ul></ul><ul><ul><li>is garbage collected </li></ul></ul><ul><ul><li>is object oriented (although to different degrees) </li></ul></ul>
  12. 12. Differences <ul><li>Everything is an object </li></ul>Java string = String.valueOf(1); Ruby string = 1.to_s() Primitive Object
  13. 13. Differences <ul><li>Many things that you would expect to be keywords are actually methods </li></ul>throw new IllegalArgumentException( &quot;oops&quot; ); raise TypeError.new( &quot;oops&quot; ) Keywords Methods
  14. 14. Differences <ul><li>Some syntax optional unless the result is ambiguous </li></ul><ul><li>These statements are equivalent </li></ul>puts( &quot;foo&quot; ); puts &quot;foo&quot; Idiomatic (better) style
  15. 15. Differences <ul><li>Classes are real objects </li></ul><ul><li>They’re instances of Class </li></ul><ul><li>Class methods can be overridden </li></ul>
  16. 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. 17. Multiline if if name. nil ? do_something end
  18. 18. Multiline if if name. nil ? do_something end Notice the question mark
  19. 19. With an else if name. nil ? do_something else something_else end
  20. 20. Single line if if name. nil ? do_something end do_something if name. nil ?
  21. 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. 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. 23. Philosophy <ul><li>Java focuses on building blocks </li></ul><ul><ul><li>You can build whatever you want with the pieces </li></ul></ul><ul><li>Ruby focuses on solving problems </li></ul><ul><ul><li>Things you do frequently should be concise </li></ul></ul>
  24. 24. Initializing arrays List<String> list = new ArrayList<String>(); list.add( &quot;foo&quot; ); list.add( &quot;bar&quot; );
  25. 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. 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. 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. 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. 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. 30. Special case for Hash hash = { :a => 5 , :b => 3 } do_stuff 30 , hash do_stuff 100 , :a => 5 , :b => 3
  31. 31. Regular Expressions Pattern pattern = Pattern.compile( &quot;^*(.+)*$&quot; ); Matcher matcher = pattern .matcher(line); if ( matcher.matches() ) { doSomething(); }
  32. 32. Regular Expressions Pattern pattern = Pattern.compile( &quot;^*(.+)*$&quot; ); Matcher matcher = pattern .matcher(line); if ( matcher.matches() ) { doSomething(); } do_something if line =~ /^s*(.+)s*$/
  33. 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. 34. Implications of late binding <ul><li>Method dispatch is quite different </li></ul><ul><li>Ruby makes a distinction between “messages” that are sent to an object and the “methods” that get dispatched </li></ul>
  35. 35. Message != Method
  36. 36. What if there isn’t a method for the specified message?
  37. 37. method_missing example from ActiveRecord user = Users.find_by_name(name) user = Users.find( :first , :conditions => [ &quot;name = ?&quot; , name])
  38. 38. Creating proxy objects <ul><li>Mock object for testing </li></ul><ul><li>Proxy object to allow distributed objects across machines </li></ul><ul><li>Wrapper to record usage of a given object </li></ul>
  39. 39. Implementing a proxy class Proxy def method_missing name, *args, &proc puts name,args end end
  40. 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. 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. 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. 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. 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. 45. Cultural differences about type <ul><li>Java is very focused on the types of objects </li></ul><ul><ul><li>Is the object an instance of a specific class? </li></ul></ul><ul><ul><li>Or does it implement a specific interface? </li></ul></ul><ul><li>Ruby is focused on the behaviour </li></ul><ul><ul><li>Does the object respond to a given message? </li></ul></ul>
  46. 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. 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. 48. Duck typing <ul><li>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 </li></ul><ul><li>&quot;If it walks like a duck and quacks like a duck, it must be a duck.&quot; -- Pragmatic Dave Thomas </li></ul>
  49. 49. How does this change how we think of types? think of types? think of types?
  50. 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. 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. 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. 53. Closures <ul><li>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 </li></ul>
  54. 54. Closures <ul><li>A closure is a block of code that you can manipulate and query </li></ul><ul><li>In Ruby we call them blocks or Procs </li></ul><ul><ul><li>A block is a pure closure </li></ul></ul><ul><ul><li>A Proc is a block wrapped as an object </li></ul></ul><ul><li>We generally use the terms block and Proc interchangeably </li></ul>
  55. 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. 56. Closures multiplier = 5 block = lambda {|number| puts number * multiplier } Parameter to the block
  57. 57. Closures multiplier = 5 block = lambda {|number| puts number * multiplier } Able to access variables from outside the block
  58. 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. 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. 60. Alternate syntax multiplier = 5 1.upto(3) {|number| puts number * multiplier } 1.upto(3) do |number| puts number * multiplier end Equivalent
  61. 61. Why are closures significant? <ul><li>Presence of closures in a language completely changes the design of the libraries </li></ul><ul><li>Closure based libraries generally result in significantly less code </li></ul>
  62. 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. 63. Closure File Example file = File. new (fileName, 'w' ) begin file.puts ‘some content’ rescue file.close end
  64. 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. 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. 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. 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. 68. Closures for Java? <ul><li>There are a couple of proposals being debated for Java7 </li></ul><ul><li>Unclear whether any of them will be accepted </li></ul><ul><li>In the past, Sun’s position has been that closures didn’t make sense at this point in Java’s evolution </li></ul>public static void main(String[] args) { int plus2(int x) { return x+2; } int(int) plus2b = plus2; System.out.println(plus2b(2)); }
  69. 69. Inheriting behaviour from multiple places <ul><li>C++ has multiple inheritance </li></ul><ul><li>Java has interfaces </li></ul><ul><li>Ruby has mixins </li></ul>
  70. 70. C++ : multiple inheritance
  71. 71. Java : inheritance
  72. 72. Ruby : mixins
  73. 73. Mixins Cannot be instantiated Can be mixed in
  74. 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. 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. 76. Enumerable <ul><li>Requires that the class implement each() </li></ul><ul><ul><li>For max, min and sort the <=> operator is also needed </li></ul></ul><ul><li>Adds many methods for modifying, searching, sorting the items </li></ul><ul><ul><li>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 </li></ul></ul>
  77. 77. Reopening classes class Foo def one puts 'one' end end
  78. 78. Reopening classes class Foo def one puts 'one' end end class Foo def two puts 'two' end end Reopening the same class
  79. 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. 80. Reopening core classes class String def one puts 'one' end end We reopened a CORE class and modified it
  81. 81. Metaprogramming <ul><li>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. </li></ul><ul><li>-- Wikipedia </li></ul>
  82. 82. What changes can we make at runtime? <ul><li>Anything we can hand code, we can programmatically do </li></ul><ul><li>Because of late binding, EVERYTHING happens at runtime </li></ul>
  83. 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. 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. 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. 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. 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. 88. Result class Foo def bar @bar end def bar=(newBar) @bar = newBar end end
  89. 89. ActiveRecord class ListItem < ActiveRecord::Base belongs_to :amazon_item acts_as_taggable acts_as_list :scope => :user end
  90. 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. 91. ObjectSpace ObjectSpace.each_object do |o| puts o end ObjectSpace.each_object(String) do |o| puts o end
  92. 92. ObjectSpace ObjectSpace.each_object do |o| puts o end ObjectSpace.each_object(String) do |o| puts o end All objects Only Strings
  93. 93. Continuations A snapshot of the call stack that the application can revert to at some point in the future
  94. 94. Why continuations? <ul><li>To save the state of the application across reboots of the VM </li></ul><ul><li>To save the state of the application across requests to a web server </li></ul><ul><ul><li>Seaside (smalltalk) does this today </li></ul></ul>
  95. 95. Downsides <ul><li>Only supported in one implementation of Ruby </li></ul><ul><li>Will be removed from the language in Ruby 2.0 </li></ul>
  96. 96. Implementations <ul><li>Ruby 1.8.x - “reference implementation” in C </li></ul><ul><li>Ruby 1.9 - Next version of C interpreter </li></ul><ul><li>Rubinius - Ruby in Ruby (sort-of) </li></ul><ul><li>Cardinal - Ruby on Parrot </li></ul><ul><li>Iron Ruby - Ruby on the DLR (Microsoft) </li></ul><ul><li>Ruby.NET - Ruby on the CLR </li></ul><ul><li>JRuby - Ruby on the JVM (Sun) </li></ul>
  97. 97. Implementations <ul><li>Ruby 1.8.x - “reference implementation” in C </li></ul><ul><li>Ruby 1.9 - Next version of C interpreter </li></ul><ul><li>Rubinius - Ruby in Ruby (sort-of) </li></ul><ul><li>Cardinal - Ruby on Parrot </li></ul><ul><li>Iron Ruby - Ruby on the DLR (Microsoft) </li></ul><ul><li>Ruby.NET - Ruby on the CLR </li></ul><ul><li>JRuby - Ruby on the JVM (Sun) </li></ul>
  98. 98. JRuby <ul><li>Runs on the Java Virtual Machine (JVM) </li></ul><ul><li>Full implementation of the Ruby language </li></ul><ul><li>Supported by Sun </li></ul><ul><li>Runs many benchmarks faster than the 1.8 reference implementation (written in C) </li></ul><ul><li>Able to easily call out to Java code </li></ul>
  99. 99. Ruby on Rails <ul><li>Web application framework </li></ul><ul><li>Sweet spot - web application talking to a single relational database </li></ul><ul><li>Allows very rapid development of web apps </li></ul>
  100. 100. Who’s using rails? <ul><li>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! </li></ul>
  101. 101. JRuby on Rails? <ul><li>Yes! You can run a rails application on JRuby in a servlet container </li></ul><ul><li>Goldspike is the servlet that dispatches to rails </li></ul><ul><ul><li>Tested on WebLogic, WebSphere, GlassFish, Jetty, Tomcat </li></ul></ul><ul><li>Warbler is the packaging tool that makes the WAR </li></ul><ul><li>Supported on: WebLogic, WebSphere, GlassFish, Jetty, Tomcat </li></ul>
  102. 102. Recap <ul><li>Learning a new language will make you better with all the languages you know </li></ul><ul><li>Ruby has a much more concise syntax which means that it takes much less code to solve the same problems </li></ul><ul><li>Ruby is able to run on the JVM which makes it an option for shops with heavy investments in J2EE infrastructure </li></ul>
  103. 103. Recap <ul><li>Everything is an object </li></ul><ul><li>The language is extremely malleable </li></ul><ul><ul><li>New classes/methods can be created on the fly </li></ul></ul><ul><ul><li>Existing classes can be modified at any time </li></ul></ul>
  104. 104. Contacting me <ul><li>Mike Bowler [email_address] www.GargoyleSoftware.com (co mpany) www.SphericalImpr ovement.com (blog) </li></ul><ul><li>Interested in le arning more about how Ruby a nd Java can coexist in your company? Just ask me. </li></ul>

×