Intro to Ruby
By Mark Menard
Enable Labs
What is a dynamic language?

 “…a class of high-level programming languages that
 execute at runtime many common behaviors that
 other languages might perform during compilation, if
 at all. These behaviors could include extension of
 the program, by adding new code, by extending
 objects and definitions, or by modifying the type
 system, all during program execution.”

 -Dynamic Programming Languages from Wikipedia
Examples of Dynamic Languages
Lisp
Scheme
Smalltalk
Perl
Lua
PHP
Javascript
Groovy
Ruby
Python

                                3
Characteristics of Dynamic Languages

Support duck typing.
Object oriented ones commonly have open classes.
Usually have a terse low ceremony syntax.
Easily support scripting.
Commonly support a REPL for interactive usage.
Some support meta-programming - “Die boiler plate die!”
 Runtime eval
 Runtime method definition
 Macros (ala Lisp)
Strong support for reflection.
Dynamic vs. Static

Dynamic Languages                          Static Languages
Variable types do not have to be           Variable types generally have to be
specified.                                 specified.
Class definitions can be modified at run   Class definitions are frozen at time of
time.                                      specification.

Standard library can be augmented.         Standard library is frozen.


Generally terse.                           Generally more verbose.
Frequently used for scripting.             Generally not used for scripting.
Usually aren’t compiled.                   Generally are compiled.
Commonly run on a Virtual Machine.         Can run on a VM or on bare metal.
Some are interpreted.

Typically support reflection.              Can support reflection.
Intro to Ruby
Dynamic Object Oriented        Mixins
 Language                       Everything is an expression
 Everything is an object       Closures
Duck typed                     Literal arrays, hashes and
Has open classes                regexes
Uses dynamic method            Operator overloading
 dispatch                       Runs on Windows, Linux,
Supports method_missing         *nix, OS X, Java, and .Net
 functionality
Support meta-programming
Executable Class Definitions
REPL
Scripting
Many dynamic languages are easily at home scripting.
Allows easy proof of concept before committing to a large
 project.
Can be used for many system administration needs.
 Full power of a multi-purpose language.




                                                             7
Terse / Low Ceremony
Ruby uses unchecked exceptions.
 No more try…catch…finally blocks everyplace.
 No more throws statements.
Cleaner syntax.
No type declarations.
See the solution not the noise.




                                                 8
REPL: irb
Access to the entire language and functionality in an interactive
 environment.
Prototype new functionality.
Explore functionality of new libraries.
Bug test problems in your code.
Interact with your application while it is running.




                                                                     9
Variables
Do not need to be declared, just use it and it springs into
 existence.
 Instance variables start with @ (ie: @name)
  M       ethod variables are just the name (ie: name = )
 Class variables start with @@ (ie: @@class_var = 1)




                                                               10
Literal Arrays, Hashes and Regex in Ruby

# Create an array
array = [ 1, 2, 3, 4, 5 ]
puts array.inspect
# Create a hash
hash = { :a => 'a', :b => 'b', 1 => 1, "a" => "string a" }
puts hash.inspect
string = "abcd"
puts string =~ /abcd/ ? ”match" : ”no match" #=> ”match"
puts string =~ /dcba/ ? ”match" : ”no match" #=> ”no match"
Classes in Ruby
class Foo
 def do_something
   puts "Foo#do_something"
 end
end

class Bar < Foo
 def do_something
   puts "Bar#do_something"
 end
end
foo = Foo.new
foo.do_something #=> prints Foo#do_something
bar = Bar.new
bar.do_something #=> prints Bar#do_something
Open Classes
Classes are open for modification at runtime.
 Methods can be added.
 Methods can be redefined.
 Methods can be added to an instance.
 Methods can be redefined on an instance.
Allows you to closely adapt the language to your problem
 domain.
 It’s like sculpting in clay instead of stone.
Mocking and stubbing become trivial.



                                                            13
Open Classes

class String

  def url_decode
    CGI::unescape(self)
  end


  def url_encode
    CGI::escape(self)
  end

end
Open Classes in Ruby
class Foo
 def escape
   puts "Whee! I'm free!"
 end
end
foo = Foo.new
foo.escape #=> prints "Whee! I'm free!"

class Foo
 def escape
   puts "Not so fast!"
 end
end

foo.escape #=> prints ”Not so fast!"
Mixins in Ruby
module Logging
 def log (msg)
  puts msg
 end
end

class OrderDispatcher
 include Logging

 def dispatch_international_order (order)
  destination = DistinationService.find(order.foreign_party)
  log("Sending #{order.number} to #{destination.name}")

  ...
 end
end
Duck Typing
“If it walks like a duck, quacks like a duck and has feathers then
 it’s a duck.”
Interfaces are conceptual, not actual.
An object’s type is defined by the messages it responds to.
Duck Typing in Ruby
class Cat               def talk
  def talk                puts "Hi"
    puts "Meow"         end
  end                 end
end
                      [ Cat.new, Dog.new, Duck.new,
class Dog             Person.new ].each do |ob|
  def talk              ob.talk
    puts "Woof"       end
  end
end

class Duck
  def talk
    puts "Quack!"
  end
end
class Person
Closures in Ruby
def create_closure (name)

 # Create a closure closing over the scope which contains 'name'
 lambda do |job|
   puts "#{name} has a new job doing #{job}."
 end
end

closure = create_closure("Mark")
closure.call("web development") #=> Mark has a new job doing web development.
closure.call("goat milking") #=> Mark has a new job doing goat milking.
Method Missing in Ruby
class MethodMissing
 def method_missing (name, *args)
   puts "Oops! Method #{name} does not exist."
 end
end
mm = MethodMissing.new
mm.foo #=> prints “Oops! Method foo does not exist.
Metaprogramming in Ruby
class MethodMissing
 def method_missing (name, *args)
   puts "method_missing called the first time."
   puts "Defining #{name} method."
   instance_eval %Q{
     def #{name.to_s} (args)
      puts "Inside the dynamically defined foo method."
     end
   }
   send(name, args)
 end
end
mm = MethodMissing.new
mm.foo(nil)
mm.foo(nil)
Operator Overloading in Ruby
class Person
 def initialize (name)
   @name = name
 end

 def + (other)
  "#{@name} and #{other.to_s} have gotten together"
 end

 def to_s
  @name
 end
end
mark = Person.new("Mark")
sylva = Person.new("Sylva")
puts mark + sylva #=> "Mark and Sylva have gotten together"

Introduction to Ruby

  • 1.
    Intro to Ruby ByMark Menard Enable Labs
  • 2.
    What is adynamic language? “…a class of high-level programming languages that execute at runtime many common behaviors that other languages might perform during compilation, if at all. These behaviors could include extension of the program, by adding new code, by extending objects and definitions, or by modifying the type system, all during program execution.” -Dynamic Programming Languages from Wikipedia
  • 3.
    Examples of DynamicLanguages Lisp Scheme Smalltalk Perl Lua PHP Javascript Groovy Ruby Python 3
  • 4.
    Characteristics of DynamicLanguages Support duck typing. Object oriented ones commonly have open classes. Usually have a terse low ceremony syntax. Easily support scripting. Commonly support a REPL for interactive usage. Some support meta-programming - “Die boiler plate die!” Runtime eval Runtime method definition Macros (ala Lisp) Strong support for reflection.
  • 5.
    Dynamic vs. Static DynamicLanguages Static Languages Variable types do not have to be Variable types generally have to be specified. specified. Class definitions can be modified at run Class definitions are frozen at time of time. specification. Standard library can be augmented. Standard library is frozen. Generally terse. Generally more verbose. Frequently used for scripting. Generally not used for scripting. Usually aren’t compiled. Generally are compiled. Commonly run on a Virtual Machine. Can run on a VM or on bare metal. Some are interpreted. Typically support reflection. Can support reflection.
  • 6.
    Intro to Ruby DynamicObject Oriented Mixins Language Everything is an expression Everything is an object Closures Duck typed Literal arrays, hashes and Has open classes regexes Uses dynamic method Operator overloading dispatch Runs on Windows, Linux, Supports method_missing *nix, OS X, Java, and .Net functionality Support meta-programming Executable Class Definitions REPL
  • 7.
    Scripting Many dynamic languagesare easily at home scripting. Allows easy proof of concept before committing to a large project. Can be used for many system administration needs. Full power of a multi-purpose language. 7
  • 8.
    Terse / LowCeremony Ruby uses unchecked exceptions. No more try…catch…finally blocks everyplace. No more throws statements. Cleaner syntax. No type declarations. See the solution not the noise. 8
  • 9.
    REPL: irb Access tothe entire language and functionality in an interactive environment. Prototype new functionality. Explore functionality of new libraries. Bug test problems in your code. Interact with your application while it is running. 9
  • 10.
    Variables Do not needto be declared, just use it and it springs into existence. Instance variables start with @ (ie: @name) M ethod variables are just the name (ie: name = ) Class variables start with @@ (ie: @@class_var = 1) 10
  • 11.
    Literal Arrays, Hashesand Regex in Ruby # Create an array array = [ 1, 2, 3, 4, 5 ] puts array.inspect # Create a hash hash = { :a => 'a', :b => 'b', 1 => 1, "a" => "string a" } puts hash.inspect string = "abcd" puts string =~ /abcd/ ? ”match" : ”no match" #=> ”match" puts string =~ /dcba/ ? ”match" : ”no match" #=> ”no match"
  • 12.
    Classes in Ruby classFoo def do_something puts "Foo#do_something" end end class Bar < Foo def do_something puts "Bar#do_something" end end foo = Foo.new foo.do_something #=> prints Foo#do_something bar = Bar.new bar.do_something #=> prints Bar#do_something
  • 13.
    Open Classes Classes areopen for modification at runtime. Methods can be added. Methods can be redefined. Methods can be added to an instance. Methods can be redefined on an instance. Allows you to closely adapt the language to your problem domain. It’s like sculpting in clay instead of stone. Mocking and stubbing become trivial. 13
  • 14.
    Open Classes class String def url_decode CGI::unescape(self) end def url_encode CGI::escape(self) end end
  • 15.
    Open Classes inRuby class Foo def escape puts "Whee! I'm free!" end end foo = Foo.new foo.escape #=> prints "Whee! I'm free!" class Foo def escape puts "Not so fast!" end end foo.escape #=> prints ”Not so fast!"
  • 16.
    Mixins in Ruby moduleLogging def log (msg) puts msg end end class OrderDispatcher include Logging def dispatch_international_order (order) destination = DistinationService.find(order.foreign_party) log("Sending #{order.number} to #{destination.name}") ... end end
  • 17.
    Duck Typing “If itwalks like a duck, quacks like a duck and has feathers then it’s a duck.” Interfaces are conceptual, not actual. An object’s type is defined by the messages it responds to.
  • 18.
    Duck Typing inRuby class Cat def talk def talk puts "Hi" puts "Meow" end end end end [ Cat.new, Dog.new, Duck.new, class Dog Person.new ].each do |ob| def talk ob.talk puts "Woof" end end end class Duck def talk puts "Quack!" end end class Person
  • 19.
    Closures in Ruby defcreate_closure (name) # Create a closure closing over the scope which contains 'name' lambda do |job| puts "#{name} has a new job doing #{job}." end end closure = create_closure("Mark") closure.call("web development") #=> Mark has a new job doing web development. closure.call("goat milking") #=> Mark has a new job doing goat milking.
  • 20.
    Method Missing inRuby class MethodMissing def method_missing (name, *args) puts "Oops! Method #{name} does not exist." end end mm = MethodMissing.new mm.foo #=> prints “Oops! Method foo does not exist.
  • 21.
    Metaprogramming in Ruby classMethodMissing def method_missing (name, *args) puts "method_missing called the first time." puts "Defining #{name} method." instance_eval %Q{ def #{name.to_s} (args) puts "Inside the dynamically defined foo method." end } send(name, args) end end mm = MethodMissing.new mm.foo(nil) mm.foo(nil)
  • 22.
    Operator Overloading inRuby class Person def initialize (name) @name = name end def + (other) "#{@name} and #{other.to_s} have gotten together" end def to_s @name end end mark = Person.new("Mark") sylva = Person.new("Sylva") puts mark + sylva #=> "Mark and Sylva have gotten together"