SlideShare una empresa de Scribd logo
1 de 49
Descargar para leer sin conexión
Ruby and OO
Cory Foy | @cory_foy
http://www.coryfoy.com
Triangle.rb
June 24, 2014
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Overview
• What is Ruby?
• Ruby Basics
• Advanced Ruby
• Wrap-up
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
What is Ruby?
• First released in 1995 by Yukihiro
Matsumoto (Matz)
• Object-Oriented
– number = 1.abs #instead of Math.abs(1)
• Dynamically Typed
– result = 1+3
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
What is Ruby?
• http://www.rubygarden.org/faq/entry/show/3
class Person
attr_accessor :name, :age # attributes we can set and retrieve
def initialize(name, age) # constructor method
@name = name # store name and age for later retrieval
@age = age.to_i 
 # (store age as integer)
end
def inspect # This method retrieves saved values
"#{@name} (#{@age})" # in a readable format
end
end
p1 = Person.new('elmo', 4) # elmo is the name, 4 is the age
puts p1.inspect # prints “elmo (4)”
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Will It Change Your Life?
• Yes!
• Ok, Maybe
• It’s fun to program with
• And what is programming if it isn’t fun?
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics
• Variables, Classes and Methods
• Properties / Attributes
• Exceptions
• Access Control
• Importing Files and Libraries
• Duck Typing
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Variables
• Local (lowercase, underscores)
– fred_j = Person.new(“Fred”)
• Instance (@ sign with lowercase)
– @name = name
• Class (@@ with lowercase)
– @@error_email = “testing@test.com”
• Constant (Starts with uppercase)
– MY_PI = 3.14
– class Move
• Global ($ with name)
– $MEANING_OF_LIFE = 42
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Variables contain
references to objects
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Classes
• Class definitions are started with
class,are named with a CamelCase
name, and ended with end
class Move
attr_accessor :up, :right
def initialize(up, right)
@up = up
@right = right
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Classes (and Modules) are
Objects
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Classes
• Attributes and fields normally go at the
beginning of the class definition
class Move
attr_accessor :up, :right
def initialize(up, right)
@up = up
@right = right
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Classes
• initialize is the same concept as a
constructor from .NET or Java, and is called
when someone invokes your object using
Move.new to set up the object’s state
class Move
attr_accessor :up, :right
def initialize(up, right)
@up = up
@right = right
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Methods
• Methods return the last expression
evaluated. You can also explicitly return from
methods
class Move
def up
@up
end
def right
return @right
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Every Expression
Evaluates to an Object
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Methods
• Methods can take in specified
parameters, and also parameter lists
(using special notation)
class Move
def initialize(up, right)
@up = up
@right = right
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
It’s All About Sending
Messages to Objects
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Methods
• Class (“Static”) methods start with
either self. or Class.
class Move
def self.create
return Move.new
end
def Move.logger
return @@logger
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Properties
• Ruby supports the concept of
Properties (called Attributes)
class Move
def up
@up
end
end
class Move
def up=(val)
@up = val
end
end
move = Move.new
move.up = 15
puts move.up #15
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Properties
• Ruby also provides convenience
methods for doing this
class Move
attr_accessor :up #Same thing as last slide
end
move = Move.new
move.up = 15
puts move.up #15
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Properties
• You can specify read or write only
attributes as well
class Move
attr_reader :up #Can’t write
attr_writer :down #Can’t read
end
move = Move.new
move.up = 15 #error
d = move.down #error
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Exceptions
• Ruby has an Exception hierarchy
• Exceptions can be caught, raised and
handled
• You can also easily retry a block of
code when you encounter an exception
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Exceptions
process_file = File.open(“testfile.csv”)
begin #put exceptional code in begin/end block
#...process file
rescue IOError => io_error
puts “IOException occurred. Retrying.”
retry #starts block over from begin
rescue => other_error
puts “Bad stuff happened: “ + other_error
else #happens if no exceptions occur
puts “No errors in processing. Yippee!”
ensure # similar to finally in .NET/Java
process_file.close unless process_file.nil?
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Access Control
• Ruby supports Public, Protected and
Private methods
• Private methods can only be accessed
from the instance of the object, not from
any other object, even those of the
same class as the instance
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Access Control
• Access is controlled by using keywords
class Move
private
def calculate_move
end
#Any subsequent methods will be private until..
public
def show_move
end
#Any subsequent methods will now be public
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Access Control
• Methods can also be passed as args
class Move
def calculate_move
end
def show_move
end
public :show_move
protected :calculate_move
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Imports
• To use a class from another file in your
class, you must tell your source file
where to find the class you want to use
require ‘calculator’
class Move
def calculate_move
return @up * Calculator::MIN_MOVE
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics - Imports
• There are two types of imports
– require
• Only loads the file once
– load
• Loads the file every time the method is executed
• Both accept relative and absolute paths, and
will search the current load path for the file
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Duck Typing
• What defines an object?
• How can you tell a car is a car?
– By model?
– By name?
• Or, by it’s behavior?
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Duck Typing
• We’d use static typing! So only the valid
object could be passed in
• What if my object has the same
behavior as a Car?
class CarWash
def accept_customer(car)
end
end
• How would we
validate this
in .NET or Java?
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Duck Typing
• What is
this?
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Duck Typing
• How
about
this?
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Duck Typing
• What
about
this?
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Duck Typing
• We know objects based on the
behaviors and attributes the object
possesses
• This means if the object passed in can
act like the object we want, that should
be good enough for us!
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Duck Typing
• Or we could just let it fail as a runtime
error
Class CarWash
def accept_customer(car)
if car.respond_to?(:drive_to)

 @car = car

 wash_car
else

 reject_customer
end
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Blocks
• A block is just a section of code
between a set of delimters – { } or
do..end
{ puts “Ho” }
3.times do
puts “Ho “
end #prints “Ho Ho Ho”
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Blocks
• Blocks can be associated with method invocations.
The methods call the block using yield
def format_print
puts “Confidential. Do Not Disseminate.”
yield
puts “© SomeCorp, 2006”
end
format_print { puts “My name is Earl!” }
-> Confidential. Do Not Disseminate.
-> My name is Earl!
-> © SomeCorp, 2006
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Blocks
• We can check to see if a block was passed to our
method
def MyConnection.open(*args)
conn = Connection.open(*args)
if block_given?
yield conn #passes conn to the block
conn.close #closes conn when block finishes
end
return conn
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Iterators
• Iterators in Ruby are simply methods
that can invoke a block of code
• Iterators typically pass one or more
values to the block to be evaluated
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Iterators
def fib_up_to(max)
i1, i2 = 1, 1
while i1 <= max
yield i1
i1, i2 = i2, i1+i2 # parallel assignment
end
end
fib_up_to(100) {|f| print f + “ “}
-> 1 1 2 3 5 8 13 21 34 55 89
• Pickaxe Book, page 50
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Modules
• At their core, Modules are like
namespaces in .NET or Java.
module Kite
def Kite.fly
end
end
module Plane
def Plane.fly
end
end
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Mixins
• Modules can’t have instances – they
aren’t classes
• But Modules can be included in
classes, who inherit all of the instance
method definitions from the module
• This is called a mixin and is how Ruby
does “Multiple Inheritance”
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Mixins
module Print
def print
puts “Company Confidential”
yield
end
end
class Document
include Print
#...
end
doc = Document.new
doc.print { “Fourth Quarter looks great!” }
-> Company Confidential
-> Fourth Quarter looks great!
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Reflection
• How could we call the Length of a
String at runtime in .NET?
String myString = "test";
int len = (int)myString

 
 .GetType()

 
 .InvokeMember("Length",
System.Reflection.BindingFlags.GetProperty,

 
 null, myString, null);
Console.WriteLine("Length: " + len.ToString());
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Reflection
• In Ruby, we can just send the
command to the object
myString = “Test”
puts myString.send(:length) # 4
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Advanced Ruby - Reflection
• We can also do all kinds of fancy stuff
#print out all of the objects in our system
ObjectSpace.each_object(Class) {|c| puts c}
#Get all the methods on an object
“Some String”.methods
#see if an object responds to a certain method
obj.respond_to?(:length)
#see if an object is a type
obj.kind_of?(Numeric)
obj.instance_of?(FixNum)
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Sending Can Be Very, Very
Bad
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Basics – Other Goodies
• RubyGems – Package Management for
Ruby Libraries
• Rake – A Pure Ruby build tool (can use
XML as well for the build files)
• RDoc – Automatically extracts
documentation from your code and
comments
Thursday, June 26, 14
Triangle.rb Meetup
June 25th, 2012
Cory Foy | @cory_foy
http://www.coryfoy.com
Ruby and OO
Ruby Resources
• Programming Ruby by Dave Thomas (the
Pickaxe Book)
• http://www.ruby-lang.org
• http://www.rubycentral.org
• http://www.ruby-doc.org
• http://www.triangleruby.com
• http://www.manning.com/black3/
• http://www.slideshare.net/dablack/wgnuby
Thursday, June 26, 14
Cory Foy
foyc@coryfoy.com
@cory_foy
blog.coryfoy.com
prettykoolapps.com
coryfoy.com
Thursday, June 26, 14

Más contenido relacionado

Destacado

GOTO Berlin - When Code Cries
GOTO Berlin - When Code CriesGOTO Berlin - When Code Cries
GOTO Berlin - When Code CriesCory Foy
 
Rails as a Pattern Language
Rails as a Pattern LanguageRails as a Pattern Language
Rails as a Pattern LanguageCory Foy
 
SQE Boston - When Code Cries
SQE Boston - When Code CriesSQE Boston - When Code Cries
SQE Boston - When Code CriesCory Foy
 
Patterns in Rails
Patterns in RailsPatterns in Rails
Patterns in RailsCory Foy
 
Collaborating with Customers using Innovation Game
Collaborating with Customers using Innovation GameCollaborating with Customers using Innovation Game
Collaborating with Customers using Innovation GameEnthiosys Inc
 
Scrum and kanban
Scrum and kanbanScrum and kanban
Scrum and kanbanAgileee
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# DevelopersCory Foy
 
Agile Roots: The Agile Mindset - Agility Across the Organization
Agile Roots: The Agile Mindset - Agility Across the OrganizationAgile Roots: The Agile Mindset - Agility Across the Organization
Agile Roots: The Agile Mindset - Agility Across the OrganizationCory Foy
 
Choosing Between Scrum and Kanban - TriAgile 2015
Choosing Between Scrum and Kanban - TriAgile 2015Choosing Between Scrum and Kanban - TriAgile 2015
Choosing Between Scrum and Kanban - TriAgile 2015Cory Foy
 
Code Katas
Code KatasCode Katas
Code KatasCory Foy
 
Stratgic Play - Doing the Right Thing at the Right Time
Stratgic Play - Doing the Right Thing at the Right TimeStratgic Play - Doing the Right Thing at the Right Time
Stratgic Play - Doing the Right Thing at the Right TimeCory Foy
 
Continuous Deployment and Testing Workshop from Better Software West
Continuous Deployment and Testing Workshop from Better Software WestContinuous Deployment and Testing Workshop from Better Software West
Continuous Deployment and Testing Workshop from Better Software WestCory Foy
 
Scrum vs Kanban - Implementing Agility at Scale
Scrum vs Kanban - Implementing Agility at ScaleScrum vs Kanban - Implementing Agility at Scale
Scrum vs Kanban - Implementing Agility at ScaleCory Foy
 
Scrum & Kanban for Social Games
Scrum & Kanban for Social GamesScrum & Kanban for Social Games
Scrum & Kanban for Social GamesWooga
 
Kanban boards step by step
Kanban boards step by stepKanban boards step by step
Kanban boards step by stepGiulio Roggero
 

Destacado (16)

GOTO Berlin - When Code Cries
GOTO Berlin - When Code CriesGOTO Berlin - When Code Cries
GOTO Berlin - When Code Cries
 
Rails as a Pattern Language
Rails as a Pattern LanguageRails as a Pattern Language
Rails as a Pattern Language
 
SQE Boston - When Code Cries
SQE Boston - When Code CriesSQE Boston - When Code Cries
SQE Boston - When Code Cries
 
Patterns in Rails
Patterns in RailsPatterns in Rails
Patterns in Rails
 
Collaborating with Customers using Innovation Game
Collaborating with Customers using Innovation GameCollaborating with Customers using Innovation Game
Collaborating with Customers using Innovation Game
 
Scrum and kanban
Scrum and kanbanScrum and kanban
Scrum and kanban
 
Ruby for C# Developers
Ruby for C# DevelopersRuby for C# Developers
Ruby for C# Developers
 
Agile Roots: The Agile Mindset - Agility Across the Organization
Agile Roots: The Agile Mindset - Agility Across the OrganizationAgile Roots: The Agile Mindset - Agility Across the Organization
Agile Roots: The Agile Mindset - Agility Across the Organization
 
Choosing Between Scrum and Kanban - TriAgile 2015
Choosing Between Scrum and Kanban - TriAgile 2015Choosing Between Scrum and Kanban - TriAgile 2015
Choosing Between Scrum and Kanban - TriAgile 2015
 
Code Katas
Code KatasCode Katas
Code Katas
 
Stratgic Play - Doing the Right Thing at the Right Time
Stratgic Play - Doing the Right Thing at the Right TimeStratgic Play - Doing the Right Thing at the Right Time
Stratgic Play - Doing the Right Thing at the Right Time
 
Continuous Deployment and Testing Workshop from Better Software West
Continuous Deployment and Testing Workshop from Better Software WestContinuous Deployment and Testing Workshop from Better Software West
Continuous Deployment and Testing Workshop from Better Software West
 
Scrum vs Kanban - Implementing Agility at Scale
Scrum vs Kanban - Implementing Agility at ScaleScrum vs Kanban - Implementing Agility at Scale
Scrum vs Kanban - Implementing Agility at Scale
 
Scrum & Kanban for Social Games
Scrum & Kanban for Social GamesScrum & Kanban for Social Games
Scrum & Kanban for Social Games
 
Kanban boards step by step
Kanban boards step by stepKanban boards step by step
Kanban boards step by step
 
Design Thinking Method Cards
Design Thinking Method CardsDesign Thinking Method Cards
Design Thinking Method Cards
 

Más de Cory Foy

Defending Commoditization: Mapping Gameplays and Strategies to Stay Ahead in ...
Defending Commoditization: Mapping Gameplays and Strategies to Stay Ahead in ...Defending Commoditization: Mapping Gameplays and Strategies to Stay Ahead in ...
Defending Commoditization: Mapping Gameplays and Strategies to Stay Ahead in ...Cory Foy
 
When Code Cries
When Code CriesWhen Code Cries
When Code CriesCory Foy
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataCory Foy
 
Mud Tires: Getting Traction in Legacy Code
Mud Tires: Getting Traction in Legacy CodeMud Tires: Getting Traction in Legacy Code
Mud Tires: Getting Traction in Legacy CodeCory Foy
 
Fostering Software Craftsmanship
Fostering Software CraftsmanshipFostering Software Craftsmanship
Fostering Software CraftsmanshipCory Foy
 
Delivering What's Right
Delivering What's RightDelivering What's Right
Delivering What's RightCory Foy
 
Koans and Katas, Oh My! From Øredev 2010
Koans and Katas, Oh My! From Øredev 2010Koans and Katas, Oh My! From Øredev 2010
Koans and Katas, Oh My! From Øredev 2010Cory Foy
 
Technically Distributed - Tools and Techniques for Distributed Teams
Technically Distributed - Tools and Techniques for Distributed TeamsTechnically Distributed - Tools and Techniques for Distributed Teams
Technically Distributed - Tools and Techniques for Distributed TeamsCory Foy
 
Growing and Fostering Software Craftsmanship
Growing and Fostering Software CraftsmanshipGrowing and Fostering Software Craftsmanship
Growing and Fostering Software CraftsmanshipCory Foy
 
IronRuby for the .NET Developer
IronRuby for the .NET DeveloperIronRuby for the .NET Developer
IronRuby for the .NET DeveloperCory Foy
 
Blackberry 101 - Day of Mobile, March 2010
Blackberry 101 - Day of Mobile, March 2010Blackberry 101 - Day of Mobile, March 2010
Blackberry 101 - Day of Mobile, March 2010Cory Foy
 
Lean and Kanban Principles for Software Developers
Lean and Kanban Principles for Software DevelopersLean and Kanban Principles for Software Developers
Lean and Kanban Principles for Software DevelopersCory Foy
 
Tools for Agility
Tools for AgilityTools for Agility
Tools for AgilityCory Foy
 

Más de Cory Foy (13)

Defending Commoditization: Mapping Gameplays and Strategies to Stay Ahead in ...
Defending Commoditization: Mapping Gameplays and Strategies to Stay Ahead in ...Defending Commoditization: Mapping Gameplays and Strategies to Stay Ahead in ...
Defending Commoditization: Mapping Gameplays and Strategies to Stay Ahead in ...
 
When Code Cries
When Code CriesWhen Code Cries
When Code Cries
 
Getting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and DataGetting Unstuck: Working with Legacy Code and Data
Getting Unstuck: Working with Legacy Code and Data
 
Mud Tires: Getting Traction in Legacy Code
Mud Tires: Getting Traction in Legacy CodeMud Tires: Getting Traction in Legacy Code
Mud Tires: Getting Traction in Legacy Code
 
Fostering Software Craftsmanship
Fostering Software CraftsmanshipFostering Software Craftsmanship
Fostering Software Craftsmanship
 
Delivering What's Right
Delivering What's RightDelivering What's Right
Delivering What's Right
 
Koans and Katas, Oh My! From Øredev 2010
Koans and Katas, Oh My! From Øredev 2010Koans and Katas, Oh My! From Øredev 2010
Koans and Katas, Oh My! From Øredev 2010
 
Technically Distributed - Tools and Techniques for Distributed Teams
Technically Distributed - Tools and Techniques for Distributed TeamsTechnically Distributed - Tools and Techniques for Distributed Teams
Technically Distributed - Tools and Techniques for Distributed Teams
 
Growing and Fostering Software Craftsmanship
Growing and Fostering Software CraftsmanshipGrowing and Fostering Software Craftsmanship
Growing and Fostering Software Craftsmanship
 
IronRuby for the .NET Developer
IronRuby for the .NET DeveloperIronRuby for the .NET Developer
IronRuby for the .NET Developer
 
Blackberry 101 - Day of Mobile, March 2010
Blackberry 101 - Day of Mobile, March 2010Blackberry 101 - Day of Mobile, March 2010
Blackberry 101 - Day of Mobile, March 2010
 
Lean and Kanban Principles for Software Developers
Lean and Kanban Principles for Software DevelopersLean and Kanban Principles for Software Developers
Lean and Kanban Principles for Software Developers
 
Tools for Agility
Tools for AgilityTools for Agility
Tools for Agility
 

Último

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 

Último (20)

why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 

Ruby and OO for Beginners

  • 1. Ruby and OO Cory Foy | @cory_foy http://www.coryfoy.com Triangle.rb June 24, 2014 Thursday, June 26, 14
  • 2. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Overview • What is Ruby? • Ruby Basics • Advanced Ruby • Wrap-up Thursday, June 26, 14
  • 3. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO What is Ruby? • First released in 1995 by Yukihiro Matsumoto (Matz) • Object-Oriented – number = 1.abs #instead of Math.abs(1) • Dynamically Typed – result = 1+3 Thursday, June 26, 14
  • 4. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO What is Ruby? • http://www.rubygarden.org/faq/entry/show/3 class Person attr_accessor :name, :age # attributes we can set and retrieve def initialize(name, age) # constructor method @name = name # store name and age for later retrieval @age = age.to_i # (store age as integer) end def inspect # This method retrieves saved values "#{@name} (#{@age})" # in a readable format end end p1 = Person.new('elmo', 4) # elmo is the name, 4 is the age puts p1.inspect # prints “elmo (4)” Thursday, June 26, 14
  • 5. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Will It Change Your Life? • Yes! • Ok, Maybe • It’s fun to program with • And what is programming if it isn’t fun? Thursday, June 26, 14
  • 6. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics • Variables, Classes and Methods • Properties / Attributes • Exceptions • Access Control • Importing Files and Libraries • Duck Typing Thursday, June 26, 14
  • 7. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Variables • Local (lowercase, underscores) – fred_j = Person.new(“Fred”) • Instance (@ sign with lowercase) – @name = name • Class (@@ with lowercase) – @@error_email = “testing@test.com” • Constant (Starts with uppercase) – MY_PI = 3.14 – class Move • Global ($ with name) – $MEANING_OF_LIFE = 42 Thursday, June 26, 14
  • 8. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Variables contain references to objects Thursday, June 26, 14
  • 9. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Classes • Class definitions are started with class,are named with a CamelCase name, and ended with end class Move attr_accessor :up, :right def initialize(up, right) @up = up @right = right end end Thursday, June 26, 14
  • 10. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Classes (and Modules) are Objects Thursday, June 26, 14
  • 11. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Classes • Attributes and fields normally go at the beginning of the class definition class Move attr_accessor :up, :right def initialize(up, right) @up = up @right = right end end Thursday, June 26, 14
  • 12. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Classes • initialize is the same concept as a constructor from .NET or Java, and is called when someone invokes your object using Move.new to set up the object’s state class Move attr_accessor :up, :right def initialize(up, right) @up = up @right = right end end Thursday, June 26, 14
  • 13. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Methods • Methods return the last expression evaluated. You can also explicitly return from methods class Move def up @up end def right return @right end end Thursday, June 26, 14
  • 14. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Every Expression Evaluates to an Object Thursday, June 26, 14
  • 15. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Methods • Methods can take in specified parameters, and also parameter lists (using special notation) class Move def initialize(up, right) @up = up @right = right end end Thursday, June 26, 14
  • 16. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO It’s All About Sending Messages to Objects Thursday, June 26, 14
  • 17. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Methods • Class (“Static”) methods start with either self. or Class. class Move def self.create return Move.new end def Move.logger return @@logger end end Thursday, June 26, 14
  • 18. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Properties • Ruby supports the concept of Properties (called Attributes) class Move def up @up end end class Move def up=(val) @up = val end end move = Move.new move.up = 15 puts move.up #15 Thursday, June 26, 14
  • 19. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Properties • Ruby also provides convenience methods for doing this class Move attr_accessor :up #Same thing as last slide end move = Move.new move.up = 15 puts move.up #15 Thursday, June 26, 14
  • 20. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Properties • You can specify read or write only attributes as well class Move attr_reader :up #Can’t write attr_writer :down #Can’t read end move = Move.new move.up = 15 #error d = move.down #error Thursday, June 26, 14
  • 21. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Exceptions • Ruby has an Exception hierarchy • Exceptions can be caught, raised and handled • You can also easily retry a block of code when you encounter an exception Thursday, June 26, 14
  • 22. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Exceptions process_file = File.open(“testfile.csv”) begin #put exceptional code in begin/end block #...process file rescue IOError => io_error puts “IOException occurred. Retrying.” retry #starts block over from begin rescue => other_error puts “Bad stuff happened: “ + other_error else #happens if no exceptions occur puts “No errors in processing. Yippee!” ensure # similar to finally in .NET/Java process_file.close unless process_file.nil? end Thursday, June 26, 14
  • 23. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Access Control • Ruby supports Public, Protected and Private methods • Private methods can only be accessed from the instance of the object, not from any other object, even those of the same class as the instance Thursday, June 26, 14
  • 24. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Access Control • Access is controlled by using keywords class Move private def calculate_move end #Any subsequent methods will be private until.. public def show_move end #Any subsequent methods will now be public end Thursday, June 26, 14
  • 25. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Access Control • Methods can also be passed as args class Move def calculate_move end def show_move end public :show_move protected :calculate_move end Thursday, June 26, 14
  • 26. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Imports • To use a class from another file in your class, you must tell your source file where to find the class you want to use require ‘calculator’ class Move def calculate_move return @up * Calculator::MIN_MOVE end end Thursday, June 26, 14
  • 27. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics - Imports • There are two types of imports – require • Only loads the file once – load • Loads the file every time the method is executed • Both accept relative and absolute paths, and will search the current load path for the file Thursday, June 26, 14
  • 28. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Duck Typing • What defines an object? • How can you tell a car is a car? – By model? – By name? • Or, by it’s behavior? Thursday, June 26, 14
  • 29. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Duck Typing • We’d use static typing! So only the valid object could be passed in • What if my object has the same behavior as a Car? class CarWash def accept_customer(car) end end • How would we validate this in .NET or Java? Thursday, June 26, 14
  • 30. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Duck Typing • What is this? Thursday, June 26, 14
  • 31. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Duck Typing • How about this? Thursday, June 26, 14
  • 32. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Duck Typing • What about this? Thursday, June 26, 14
  • 33. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Duck Typing • We know objects based on the behaviors and attributes the object possesses • This means if the object passed in can act like the object we want, that should be good enough for us! Thursday, June 26, 14
  • 34. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Duck Typing • Or we could just let it fail as a runtime error Class CarWash def accept_customer(car) if car.respond_to?(:drive_to) @car = car wash_car else reject_customer end end end Thursday, June 26, 14
  • 35. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Blocks • A block is just a section of code between a set of delimters – { } or do..end { puts “Ho” } 3.times do puts “Ho “ end #prints “Ho Ho Ho” Thursday, June 26, 14
  • 36. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Blocks • Blocks can be associated with method invocations. The methods call the block using yield def format_print puts “Confidential. Do Not Disseminate.” yield puts “© SomeCorp, 2006” end format_print { puts “My name is Earl!” } -> Confidential. Do Not Disseminate. -> My name is Earl! -> © SomeCorp, 2006 Thursday, June 26, 14
  • 37. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Blocks • We can check to see if a block was passed to our method def MyConnection.open(*args) conn = Connection.open(*args) if block_given? yield conn #passes conn to the block conn.close #closes conn when block finishes end return conn end Thursday, June 26, 14
  • 38. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Iterators • Iterators in Ruby are simply methods that can invoke a block of code • Iterators typically pass one or more values to the block to be evaluated Thursday, June 26, 14
  • 39. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Iterators def fib_up_to(max) i1, i2 = 1, 1 while i1 <= max yield i1 i1, i2 = i2, i1+i2 # parallel assignment end end fib_up_to(100) {|f| print f + “ “} -> 1 1 2 3 5 8 13 21 34 55 89 • Pickaxe Book, page 50 Thursday, June 26, 14
  • 40. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Modules • At their core, Modules are like namespaces in .NET or Java. module Kite def Kite.fly end end module Plane def Plane.fly end end Thursday, June 26, 14
  • 41. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Mixins • Modules can’t have instances – they aren’t classes • But Modules can be included in classes, who inherit all of the instance method definitions from the module • This is called a mixin and is how Ruby does “Multiple Inheritance” Thursday, June 26, 14
  • 42. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Mixins module Print def print puts “Company Confidential” yield end end class Document include Print #... end doc = Document.new doc.print { “Fourth Quarter looks great!” } -> Company Confidential -> Fourth Quarter looks great! Thursday, June 26, 14
  • 43. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Reflection • How could we call the Length of a String at runtime in .NET? String myString = "test"; int len = (int)myString .GetType() .InvokeMember("Length", System.Reflection.BindingFlags.GetProperty, null, myString, null); Console.WriteLine("Length: " + len.ToString()); Thursday, June 26, 14
  • 44. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Reflection • In Ruby, we can just send the command to the object myString = “Test” puts myString.send(:length) # 4 Thursday, June 26, 14
  • 45. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Advanced Ruby - Reflection • We can also do all kinds of fancy stuff #print out all of the objects in our system ObjectSpace.each_object(Class) {|c| puts c} #Get all the methods on an object “Some String”.methods #see if an object responds to a certain method obj.respond_to?(:length) #see if an object is a type obj.kind_of?(Numeric) obj.instance_of?(FixNum) Thursday, June 26, 14
  • 46. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Sending Can Be Very, Very Bad Thursday, June 26, 14
  • 47. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Basics – Other Goodies • RubyGems – Package Management for Ruby Libraries • Rake – A Pure Ruby build tool (can use XML as well for the build files) • RDoc – Automatically extracts documentation from your code and comments Thursday, June 26, 14
  • 48. Triangle.rb Meetup June 25th, 2012 Cory Foy | @cory_foy http://www.coryfoy.com Ruby and OO Ruby Resources • Programming Ruby by Dave Thomas (the Pickaxe Book) • http://www.ruby-lang.org • http://www.rubycentral.org • http://www.ruby-doc.org • http://www.triangleruby.com • http://www.manning.com/black3/ • http://www.slideshare.net/dablack/wgnuby Thursday, June 26, 14