Justin Mui

Justin Mui

Objects

Slide Duration:

Table of Contents

Section 1: Introduction to Ruby
Setting Up Your Environment

22m 8s

Intro
0:00
Installing Ruby
0:06
Ruby-lan.org
0:07
Three Ways of Installing Ruby
2:26
Compiling Ruby-Source Code
3:02
Third Party Tools
3:28
Other Implementations of Ruby
4:48
Windows Installation
5:21
RubyInstaller.org
5:22
Mac OSX and Linux Installation
6:13
Mac OSX and Linux Installation
6:14
Setting Up Debian/Linux
6:42
Setting Up Debian/Linux
6:43
Installing HomeBrew
6:56
HomeBrew for MAC OSX
6:57
HomeBrew Wiki
9:44
Installing HomeBrew
10:02
Setting Up Mac OSX
11:46
HomeBrew, RVM, OSX-GCC Installer, and Install Ruby 1.9.3
11:47
Ruby Version Manager (RVM)
12:11
Ruby Version Manager (RVM) Overview
12:12
Installing Ruby Version Manager (RVM): http://rvm.io
12:35
Install RVM with Ruby
14:20
Install RVM with Ruby
14:21
Install OSX-GCC-Installer
16:18
Download and Install Package for Your OSX
16:19
Install Ruby 1.9.3
17:28
Install Ruby 1.9.3
17:29
Test It Out!
18:09
rvm-help & ruby-v
18:10
Example: rvm gemset create educator
18:52
Set It As Default!
20:47
rvm Use 1.9.3@educator--default
20:48
Intro to Ruby

22m 20s

Intro
0:00
What is Ruby?
0:06
What is Ruby?
0:07
Ruby Standard Library
0:52
Who Created Ruby?
1:22
Yukihiro Matsumoto
1:23
History
2:45
The Name 'Ruby'
2:46
Ruby v0.95
3:10
Ruby v1.0
3:56
English Language Mailing List Rubytalk
4:08
ruby-forum.com & the Mailing Lists
4:27
Ruby In The West
9:51
Ruby on Rails
10:39
The Pragmatic Programmer's Guide to Ruby
11:30
rubyonrails.org
13:34
Current Ruby
14:42
Ruby 1.8.7, Ruby 1.9.3, and Ruby 2.0
14:43
Why Programmers Enjoy Ruby?
15:40
Why Programmers Enjoy Ruby?
15:41
Ruby Is An Interpreted Language
16:21
Ruby Is An Interpreted Language
16:22
What Is It Used For?
16:50
What Is It Used For?
16:51
Ruby is Object-Oriented
18:17
Example: 5.class
18:18
Example: 0.0.class
18:54
Example: true.class
19:03
Example: nil.class
19:12
Object Class
19:19
BasicObject
19:20
Example
19:52
Superclass
20:50
Fixnum → Integer → Numeric → Object
21:32
Basic Tools for Using Ruby

27m 44s

Intro
0:00
Interactive Ruby
0:08
irb: Interactive Command-Line Environment
0:09
Example
0:49
irb-v
0:50
irb-executes terminal
1:02
1.9.3-p125 > 'hi'
1:09
Live Demonstration
1:31
Why Use Interactive Ruby?
2:21
Why Use Interactive Ruby?
2:22
RDoc
3:05
RDoc
3:06
Ruby Core Documentation
3:32
Ruby Core Documentation: Example
5:30
Ruby Core Documentation: Markup
6:12
Ruby Core Documentation: Headings
7:44
Coding Example: RDoc
9:30
Why Use RDoc?
13:02
Learning Core Ruby Functions
13:03
Generating RDoc
15:31
rdoc-help # usage
15:32
Ruby Interpreter
15:57
ruby -- help
15:58
ruby [switches] [-] program [arguments]
16:16
Example: How to Run a Ruby Script
16:28
Rake
18:38
Rake Overview
18:39
Ruby Core Documentation: Rake
19:46
Coding Example: Rake
23:14
Why Was It Created?
24:30
Why Was It Created?
24:31
Lesson Summary
25:13
Lesson Summary
25:14
IDE/script Editors: MacVIM
26:24
Ruby Specifics

20m 45s

Intro
0:00
Ruby Specifics
0:06
Comments
0:51
Hashtags
1:00
Example
1:23
Multi-Line Comment
2:04
Example
3:10
RDoc Comments
4:02
When do you generate an Rdoc?
4:10
Headings and subheadings
4:24
Examples
4:48
Generating an Rdoc - example
4:50
Common Code Conventions
6:28
For every tab use two spaces indentation
7:38
Never use tabs
7:42
Common Code Conventions (Cont.)
8:18
Camel case
8:20
Snake case
9:18
Identifiers
9:44
Constants begin with CAP letter
10:00
Examples
10:10
Identifiers with Different Scoping
10:26
Global
10:34
Instance Variable
10:40
Class Variable
10:46
Examples
10:56
Reserved Keywords
12:22
Do not use reserved keywords in code
12:25
Parentheses are Sometimes Optional
13:04
Functions do not require parentheses
13:16
When in doubt, use parentheses
13:54
Examples
14:10
Newlines Are Statement Terminators
14:20
Examples
15:10
Continuation with a Period
16:20
Period means continue to next line
16:46
Multiple Statements Allowed on a Single Line
17:38
Try not to use semi-colons
17:58
Code Blocks
18:20
Use code blocks for one liners
18:28
Examples
18:40
Recommended for multiple lines
20:16
Ruby Data Types (Part 1)

29m 37s

Intro
0:00
Overview
0:10
Ruby Data Types
0:10
Numbers
0:16
Strings
0:18
Symbols
0:24
Numbers
0:30
Numeric
0:44
Float
0:50
Complex
0:56
BigDecimal
0:58
Rational
1:00
Integer (most popular) - Fixnum and Bignum
1:06
Fixnum stores 31 bits
1:18
Bignum stores larger bits
1:24
All number objects are instances of Numeric
1:28
Integer Literals
2:28
Represent whole-numbers
2:40
Examples - Different bases
2:42
Binary
3:04
Octal
3:30
Hexadecimal
3:44
Examples
4:06
Floating Point Literals
4:45
Examples
4:58
e-value can be capital or lowercase
5:30
Example
5:44
Strings
6:16
Mutable objects
6:18
Used for inserting and deleting text, searching, and replacing
6:26
String Rdoc
6:46
Definition
7:00
String Literals
8:20
Single-Quoted
8:28
Double-Quoted (most used)
8:50
Example
9:32
Escape Sequences
11:10
Newline
11:16
Tab
11:22
Double quote
11:28
Blackslash
11:36
Interpolation
11:50
Sprintf
13:48
Unicode Escaping
14:38
Example
15:50
Delimiters
16:18
Here Documents
17:18
Example
17:25
String Operators
19:58
Concatenation
20:03
Appending
20:40
String Equality
21:04
Example
21:24
Substrings
22:00
Range object (inclusive)
22:22
String Encoding
24:52
Differences between Ruby 1.8 and 1.9
24:56
Symbols
26:02
Definitions
26:04
Examples
26:46
When to use symbols
26:54
Symbols and Strings
27:42
Symbols Rdoc
28:22
Ruby Gems

25m 50s

Intro
0:00
RubyGems
0:08
What are RubyGems?
0:24
RubyGems.org
0:44
How RubyGems are used
2:06
Java's jar utility
2:50
Unix/Linux's tar utility
3:06
What is a Gem?
3:16
Definition of Gem
3:20
Version
3:34
Date
3:44
Author
3:50
Description
5:58
What Are the Uses?
4:18
Uses for Gems
4:22
Installation
5:06
How to install RubyGems
5:30
Updating to the Latest Ruby Gems
5:54
Testing
6:22
Example
6:34
Installing Rake
7:24
Example
7:46
Verifying
9:22
Example
9:56
Structure
10:56
gem.gemspec
11:30
Specification
13:40
What is in the gem?
13:42
Who made it?
13:50
Update gem version
13:58
Example
14:10
Create Our First Gem
17:20
Steps involved
17:28
RubyGems Guides
17:36
Example
20:02
Steps Review
18:56
Create Our First Gem (Cont.)
23:08
Building the gem
19:38
Example
20:00
Installing the gem
22:32
Run it
22:52
Publish it
23:04
Get Some Gems!
25:06
rake
25:14
rails
25:19
fastercsv
25:25
koala
25:37
Ruby Data Types (Part 2)

40m 24s

Intro
0:00
Ruby Data Types
0:15
Boolean
0:21
Arrays
0:27
Hashes
0:33
Range
0:37
Boolean Types
0:42
TrueClass
0:56
FalseClass
1:12
NilClass
1:18
TrueClass Examples
2:48
FalseClass Examples
3:22
Arrays
4:16
Ordered collection of objects
4:22
Can hold different objects
4:32
Starts at index 0
4:50
Array of Strings
5:50
Example
5:52
Arrays (Cont.)
6:20
Can be created using literals
6:22
Can be created using constructors
6:54
Position and indexed value
8:04
Negative Indexed Values
8:56
Shift and Unshift
10:18
Push and Pop
11:38
.delete method
12:38
Addition and Subtraction
13:32
Union and Intersection
14:48
Insert
15:52
Iteration
16:52
Arrays Rdoc
17:48
Hashes
22:08
Maps and Associative Arrays
22:44
Created using the constructor
22:56
Created using a hash literal
24:02
Stored in a hash table
25:26
Example
25:50
Accessing Key-Values
27:46
Deletion
29:48
Iteration
31:04
Hashes Rdoc
32:04
Ranges
36:40
Two dots are inclusive
36:57
Three dots are exclusive
37:16
Example
37:50
Ranges Rdoc
38:24
Objects

1h 5m 46s

Intro
0:00
Objects
0:10
Object References
1:36
Ruby Core
2:16
Example
4:30
Creating New Objects
6:00
New Method
6:08
Initialize Method
6:31
Example
7:18
Garbage Collection
9:54
Global values always reachable
10:25
Object Identity
11:08
Every object has an object identifier
11:20
Object identifier is constant and unique
11:30
Example
11:54
Object Class
12:58
Class method
13:10
Superclass method
13:28
Object Testing
14:46
is_a?
15:49
respond_to?
16:26
String and Regexp
18:10
Comparing two object instances
20:06
Example
23:30
Object Equality
25:48
Comparing objects
25:54
equal?
25:58
Popular way to test for equality
27:16
Opposite way to test for equality
27:25
Arrays
28:30
Hash
29:42
Case equality operator
30:47
Class tests
31:16
Range tests
31:48
Symbol tests
32:32
Object Conversion
33:14
Explicit conversion
33:54
Implicit conversion
35:00
Example
36:12
Object Conversion: Kernel Module
38:22
Array
38:38
Float
39:26
Integer
39:58
String
40:10
Example
40:34
Object Conversion: Coerce
42:00
Used for mixed type numeric operations
42:08
Example
43:40
Object Conversion: Boolean
47:42
Every object has a boolean value
47:44
Example
48:54
Object Copying
50:52
dup
50:58
clone
51:03
Example
51:42
Object Freezing
57:36
Object Marshaling
58:38
Save state
59:04
Load state
59:27
Example
59:32
Tainted Objects
1:01:50
taint
1:02:08
farm field
1:02:12
Untrusted Objects
1:04:06
trust
1:04:24
untrust
1:04:34
untrusted?
1:04:42
Loops

38m 54s

Intro
0:00
Loops
0:12
while and until
0:48
for and in
0:54
iterators
1:04
enumerable in objects
1:06
While-loop
1:14
Will keep going is condition is true
1:18
Until-loop
2:58
Will keep going until condition becomes true
3:06
Single Expression Loops
4:20
Compact form
4:30
Expressed as a modifier
4:42
Do-While Loop
5:52
Executes body first
6:06
Do-Until Loop
7:54
Similar to do-while loop
7:58
Using Break Inside Loops
8:54
break
8:58
For-In Loop
11:56
for-loop
12:06
var
12:34
collection
12:54
body
13:00
Examples
13:08
Examples (Cont.)
15:54
Nested loops
16:40
Numeric Iterators
18:32
upto
18:40
downto
18:42
times
18:48
Examples
20:28
External Iterators
21:00
Enumerator class
21:04
Rdoc
21:16
Enumerables in Objects
24:35
Enumerable is a mix-in
24:41
RDoc
25:24
Commonly Used Enumerables in Objects
27:01
Array
27:19
Hash
27:51
Range
28:47
Examples
29:29
Enumerables in Objects (Cont.)
31:13
File Processing
31:15
Example
31:45
Enumerables in Objects (Cont.)
33:07
collect
33:23
select
34:11
reject
34:59
inject
35:29
Strings

28m 30s

Intro
0:00
Strings
0:08
Why do you want to get familiar with strings?
1:00
String Creation
1:16
new
1:28
empty?
1:50
length or size
2:10
Example
3:12
String Manipulation
4:40
slice
4:56
square brackets [ ]
5:02
token
5:40
[fixnum]
6:52
offset and length
8:40
chaining
12:42
String Insertion
12:56
insert
12:58
positive or negative index
13:46
String Updates
15:24
[token]
15:36
Examples
16:40
chop or chop!
17:54
chomp!
18:56
gsub
20:28
String Deletion
21:38
delete
21:38
String Reversal
22:46
reverse
22:52
String Manipulation
23:16
split(pattern=$, limit)
23:22
pattern
24:10
limit
24:15
upcase or upcase!
25:28
downcase or downcase!
26:02
swapcase
26:24
Incrementing Strings
27:26
next or next!
27:32
Check Out the Other Lessons
28:00
Ruby Data Types Part 1
28:12
Regular Expressions
28:18
Regular Expressions

33m 27s

Intro
0:00
Regular Expressions
0:10
How to create a regular expression
0:48
What goes inside
1:36
Metacharacters
3:10
Bracket expressions
3:14
Quantifiers
3:18
Anchors
3:20
Metacharacters
3:30
word and non-word characters
4:04
digit and non-digit characters
4:44
hexdigit and non-hexdigit characters
4:56
whitespace and non-whitespace characters
5:08
Examples
5:24
POSIX Bracket Expressions
7:48
Non-POSIX Bracket Expressions
9:48
Bracket Expression Examples
10:58
Quantifiers
12:34
Examples
13:30
Character Properties
17:24
Similar to POSIX bracket classes
18:22
More Character Properties
18:48
Examples
19:32
Anchors
20:08
Examples
21:14
Regular Expression Matching: Regexp Object
22:40
match
22:51
Regular Expression Matching: String Object
24:14
match
24:26
Regular Expression Modifier Characters
25:14
pat
25:38
Example
26:42
Regular Expression Modifier Objects
27:14
Example
28:38
Regexp Rdoc
30:40
Arrays

14m 35s

Intro
0:00
Arrays
0:12
Creating an Array with a Block
0:50
Alternative Ways to Create an Array
3:52
Checking the Class
5:14
Iterate through the array
5:26
Call the class method
5:28
Array Shortcuts
6:38
at(index)
6:44
delete_at(index)
7:28
first(n)
8:28
last(n)
9:28
Removing Duplicates
9:58
uniq or uniq!
10:04
Sorting the Array
10:48
sort or sort!
10:54
Getting the Index
11:35
index
11:56
rindex
12:38
Multidimensional Arrays
12:56
flatten
13:33
Check Out the Earlier Lesson
14:16
Ruby Data Types Part 2
14:26
Hashes

27m 48s

Intro
0:00
Hashes
0:12
Creating Hashes
1:18
Setting a Default Value
2:24
Accessing Hashes
4:16
Accessible by keys or by values
4:28
Keys must be unique
4:36
Creating Hashes
5:16
Comma-separated list
5:42
Hash rocket
8:28
Examples
10:16
Iterating Keys and Values
11:43
each_key
12:04
each_value
14:04
Merging Hashes
16:10
merge(other_hash)
16:20
Sorting Hashes
18:46
Replacing Hashes
20:57
replace(other_hash)
21:18
Converting Hashes to Other Classes
22:04
to_a
22:22
to_s
23:22
Example
24:34
Check Out the Earlier Lesson
27:22
Ruby Data Types Part 2
27:32
Math Operations, Part 1

28m 47s

Intro
0:00
Math Objects
0:12
Numeric
0:26
Integer
0:38
Float
1:02
Fixnum
1:14
Bignum
1:56
Rational
2:04
Math
2:24
Math Operations
2:36
Example
3:14
div(numeric)
4:54
divmod(numeric)
6:30
modulo(numeric)
7:23
quo(numeric)
8:18
remainder(numeric)
9:35
Operation Precedence 1 of 3
10:35
Operation Precedence 2 of 3
13:18
Operation Precedence 3 of 3
14:28
Abbreviated Math Operations
14:54
Move the operator in front of the equal sign
15:52
Numbers
16:36
Numeric Class
17:06
Numeric Methods
18:41
ceil
18:52
floor
19:32
round
19:50
Example with Numbers
20:20
Numeric Methods (Cont.)
22:20
truncate
22:28
num.step(limit, step)
23:02
Numeric Rdoc
25:26
Math Operations, Part 2

28m 51s

Intro
0:00
Math Operations
0:12
Math Module
0:24
Rational Numbers
0:44
Complex Numbers
0:52
Prime Numbers
0:58
Matrices
1:06
Math Module
1:12
PI and E
1:32
Math Module Methods
2:47
atan2(x,y)
2:56
cos(x)
3:14
exp(x)
3:44
Examples
4:38
log(x)
5:44
log(num, base)
6:34
log10(x)
7:04
sin(x)
7:34
sqrt(x)
7:52
tan(x)
8:06
Math Functions: Part 1 of 3
8:12
Math Functions: Part 2 of 3
9:32
Math Functions: Part 3 of 3
10:19
Math Module Rdoc
11:25
Rational Numbers
13:23
How to use
14:06
Example
15:02
Mathematical Ruby Scripts (Mathn)
16:25
Example
17:28
Complex Numbers
18:26
polar
18:56
rect
19:10
Complex Number Examples
19:18
Prime Numbers
20:14
each(ubound=nil)
20:44
prime?
21:22
Example
21:58
Matrices
23:15
build(row_size, column_size=row_size)
23:44
Example
24:44
Matrix Rdoc
24:58
Dates and Times

26m 1s

Intro
0:00
Dates and Times
0:12
Time Class
0:38
Methods of the Time Class
1:43
now
1:44
at(time)
2:10
Epoch & Unix Timestamp Conversion Tools
3:19
Components of a Time
5:07
Convert Time to an Array
5:54
to_a
6:08
Creating a New Time
6:48
Time.local
7:08
Year is required
7:22
Time.utc
8:12
What should be specified
9:30
More Methods of the Time Class
10:16
strftime(string)
11:26
RDoc
12:50
Date Library
16:46
Initializing a New Date
17:08
Parsing Dates
18:28
parse(string)
18:42
Today's Date
19:19
Date.today
19:22
Tomorrow's Date
20:22
Next
20:28
Next week
21:22
Count Down
21:26
Count Up
22:37
Components of a Date
23:20
Converting to Datetime
23:48
to_datetime
24:00
Initializing a Datetime
24:24
Converting to Time
25:23
self.to_time
25:32
Methods: Part 1

31m 24s

Intro
0:00
What is a Method?
0:12
Basic Method
0:58
Return Value
4:37
return
4:46
Factorial Example
6:18
Example
8:46
Return Two Values
10:06
Set the return keyword
10:14
Collected and returned as an array
10:28
Undefining Methods
11:22
undef method_to_undefine
11:44
Example
12:32
Method Names
13:02
Begin with lowercase letter
13:16
Separate longer words with underscores
13:26
Can end with equal sign, question mark, or exclamation point
14:03
Equal sign
14:26
Method Names with Question Mark
14:44
empty?
15:24
Method Names with Exclamation Point
16:01
mutators
16:12
! means use with caution
16:46
Method Aliases
18:05
alias new_method existing_method
18:42
Operator Methods
20:00
Operators
20:02
Array Operators
20:10
Unary Operators
20:32
Binary Operators
20:40
Example
21:28
Methods and Parentheses
25:00
Optional in most cases
25:20
Required in other cases
27:13
Methods and Blocks
27:54
Associated with blocks
28:18
block_given?
28:26
yield
28:36
Example
29:24
Methods: Part 2

20m 11s

Intro
0:00
Methods with the Unary Ampersand Operator
0:14
&
0:34
Block to a Proc
0:56
Example
2:02
Proc object
3:58
Example
5:04
Methods with Default Values
5:54
Example
7:12
Methods with variable-Length Arguments
8:05
How to create it
8:36
Example
11:06
Using Hashes with Arguments
13:02
Multiple arguments
13:08
Solution
13:30
Example
14:56
Rdoc
18:12
Classes: Part I

26m 51s

Intro
0:00
Classes
0:10
Definition of a class
0:14
Class represents a container
0:32
Can be reused
0:46
Creating our First Class
1:00
Keyword class will create new class
1:06
Name must begin with capital letter
1:30
Instantiating Our First Class
2:46
New will create a new instance of class
2:58
Initializing Values
3:58
Definition of def
4:14
Instance method
5:08
Example
7:02
Defining the to_s Method
8:24
Creating a string representation class
8:34
Example
10:54
Self in the Class
12:16
Definition of self
12:26
Example
13:54
Accessor Methods
15:52
getter methods
16:22
Example
17:00
Setter Methods
18:00
Mutator methods
18:02
Example
19:46
Automating Getter and Setter Methods
21:10
Defined in the module class
21:30
attr_reader
21:54
attr_writer
22:48
attr creates getter and setter methods
23:50
Example
24:28
Notes on Ruby's Accessor Methods
25:32
Classes: Part II

26m 42s

Intro
0:00
Defining Operators
0:10
You can define arithmetic operators
0:32
Unary Operators
0:46
Let's define operators in our class!
0:56
Example
2:52
Class Methods
6:24
Examples
6:56
Opening Up the Class
9:38
Adds an additional method
9:54
Examples
11:04
Array and Hash Access Method
15:40
Use square brackets
16:02
Define your own has access method
16:08
Example
16:56
Enumerating The Values
18:40
Define the each iterator
18:40
Testing for Equality
19:36
Class Triplex
19:50
Examples
20:54
Constants
25:00
Usually defined at the top of class
25:24
Classes: Part III

53m 36s

Intro
0:00
Class Variables
0:14
Example
2:16
Ruby Glass Jar Example
8:50
Class Instance Variables
10:20
Instance variables of class objects
10:46
Advantage of class instance variables
11:18
Examples
11:30
Method Visibility
16:16
Three types of method visibility
16:26
Public methods
17:34
Private methods
17:38
Protected methods
18:04
Invoking Method Visibility
19:21
Public , Protected, and Private Visibility
19:22
Invoking Method Visibility With Arguments
21:39
Example: Invoking Method Visibility
22:12
Class Visibility
23:31
Instance and Class Variables are Private
23:32
Constants are Public
24:00
Makes Existing Class Methods Private
24:27
Makes Existing Class Methods Public
25:08
Example: Class Visibility and class GlassJar
25:43
Subclassing
27:08
Subclassing: Subclass and Superclass
27:09
Example: Subclassing
29:43
Inheritance
30:05
Inheritance
30:06
Example: Inheritance
31:25
Subclassing and Inheritance
31:34
Descendants
31:41
Ancestors
31:56
More On Descendants and Ancestors
32:08
Extending a Class
33:27
Extending a Class
33:28
Coding Example: Extending a Class
34:24
Overriding a Method
36:41
Overriding a Method
36:42
Coding Example: Overriding a Method
37:18
Modifying Methods with Chaining
38:52
Modifying Methods with Chaining
38:53
Super
39:25
Coding Example: Modifying Methods with Chaining
39:51
The Singleton Pattern
44:52
Introduction to The Singleton Pattern
44:53
Setting Up Singleton
45:28
The Instance Method
45:58
Rdoc for Singleton: Usage
46:23
Rdoc for Singleton: Implementation
47:45
Coding Example: Singleton
49:38
Modules

24m 19s

Intro
0:00
Modules
0:04
What is Modules?
0:05
Modules Examples
0:40
Modules: Mix-Ins
3:31
What is a Mix-in?
3:32
Modules: Namespace
4:07
What is a Namespace?
4:08
Why Use a Namespace?
5:13
Example of a Namespace Module
5:59
Example of Mixing in The Module Into the Global Scope
6:00
Modules: Creation
7:04
How to Create a New Module?
7:05
Modules: Usage
8:19
How to Use It?
8:20
class Poker & class Bridge
9:13
Creating Our Module as a Mix-In
9:41
Example of a Module Using Instance Methods
9:42
Coding Example
10:20
Creating Our Module as a Namespace
12:11
Implement Class Methods for the Module
12:12
Coding Example
14:56
Loading Our Module
19:46
Loading Our Module Overview
19:47
Require & Load
20:15
Coding Example: Loading Module
20:48
Lesson Summary
23:36
Loading...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Introduction to Ruby
Bookmark & Share Embed

Share this knowledge with your friends!

Copy & Paste this embed code into your website’s HTML

Please ensure that your website editor is in text mode when you paste the code.
(In Wordpress, the mode button is on the top right corner.)
  ×
  • - Allow users to view the embedded video in full-size.
Since this lesson is not free, only the preview will appear on your website.
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for Educator.com

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

Objects

  • Ruby is a pure object-oriented language
  • All values are objects
  • The garbage collection will automatically destroy objects when they are no longer reachable
  • Every object has an object identifier
  • class method will determine the class of the object
  • superclass method will determine the parent's class
  • instance_of? method checks the class of the object
  • respond_to? method allows you to test if you can invoke a method
  • equal? method check if they refer to the same object
  • Every object has their own definition for equality "==":
  • Array objects need to have the same number of elements and each element needs to be equal.
  • Hash objects need to have the same number of key-value pairs and each key-value is equal.
  • === is the case equality operator
  • String checks if the object is an instance of its class
  • Range tests if the object belongs in the range
  • Symbol tests if the string has the same text as the symbol
  • Ruby allows objects to be converted to a different class through explicit and implicit conversion
  • The Kernel Module allows conversions to Array, Float, Integer, and String
  • RDoc: http://www.ruby-doc.org/core-1.9.3/Kernel.html
  • Coerce is intended to find a common type between two operands
  • Both dup and clone create shallow copies by default
  • Frozen objects are immutable
  • Objects can be marked tainted and trusted

Objects

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Objects 0:10
  • Object References 1:36
    • Ruby Core
    • Example
  • Creating New Objects 6:00
    • New Method
    • Initialize Method
    • Example
  • Garbage Collection 9:54
    • Global values always reachable
  • Object Identity 11:08
    • Every object has an object identifier
    • Object identifier is constant and unique
    • Example
  • Object Class 12:58
    • Class method
    • Superclass method
    • Object Testing
    • is_a?
    • respond_to?
    • String and Regexp
    • Comparing two object instances
    • Example
  • Object Equality 25:48
    • Comparing objects
    • equal?
    • Popular way to test for equality
    • Opposite way to test for equality
    • Arrays
    • Hash
    • Case equality operator
    • Class tests
    • Range tests
    • Symbol tests
  • Object Conversion 33:14
    • Explicit conversion
    • Implicit conversion
    • Example
  • Object Conversion: Kernel Module 38:22
    • Array
    • Float
    • Integer
    • String
    • Example
  • Object Conversion: Coerce 42:00
    • Used for mixed type numeric operations
    • Example
  • Object Conversion: Boolean 47:42
    • Every object has a boolean value
    • Example
  • Object Copying 50:52
    • dup
    • clone
    • Example
  • Object Freezing 57:36
  • Object Marshaling 58:38
    • Save state
    • Load state
    • Example
  • Tainted Objects 1:01:50
    • taint
    • farm field
  • Untrusted Objects 1:04:06
    • trust
    • untrust
    • untrusted?

Transcription: Objects

Welcome back to Educator.com.0000

Today's lesson is on objects.0002

Objects are a pure object-oriented language.0011

Everything in Ruby is an object, as we've gone through in other lessons.0018

All values are objects, and there is no distinction between primitive types and object types.0029

All objects inherit from an object.0041

The reason on this third part--we say that there is no distinction between primitive types and object types--if you come from other languages, and you are looking at int values or even Booleans, usually they have a primitive type for that.0047

But, in Ruby, you know that you already have your TrueClass; you have your FalseClass; you have your Integer class, your Boolean class...so everything is still just an object.0061

For this slide, we are going to talk about object references.0096

Whenever you are coding in Ruby, you are not actually making code for an object.0101

You are actually making and developing the code for the object reference.0107

Every time you are programming, you are actually using a reference of the code; you are instancing the code, creating a constructor, and you are working with the reference of it.0112

Especially if we are working with the already-built-in Ruby core...0125

That is why, here, I say this is what we work with.0132

When we work with the Ruby core--any of the Ruby core libraries--we are working with references; we're not creating the actual classes for this; it has already been created.0137

We are just using those classes to do our development in our code.0149

So, we just do the updates, the modifications, and the creations for those references.0155

We have an example here.0164

What we are going to do is: First, we are going to create array.new.0166

It is going to be stored as an Array object entitled Fruits.0176

Here, what we are doing is creating another value, called Foods, that equals Fruits.0182

This is going to copy the reference to Foods.0189

Here, on the next line, we do a foods.push(apple), so it stores 'apple' into the Foods Array.0196

Then, you do a .push(cherries), which also pushes it into that Foods Array.0205

Take a look, now: we have our Array with 'apple' and 'cherries'.0209

Now, if you print that Array out, the Food and Fruits will have the same Array.0228

But, if you create a new Array with Foods, you will notice, if you print Foods and Fruits, that they are actually different references now.0238

One is pointing to an extension .new Array object, and the other one still has this 'apple' and 'cherries'.0248

Let's see it in action so you have a better idea.0257

What I am going to do here is just to launch the IRB.0266

Let's go ahead and use that first example.0270

We have our empty Array of Fruits; now, I'm going to point Foods to Fruits, so we have a reference--again, an empty Array; now let's go ahead and push those elements there.0275

Notice, we are chaining the elements together, so we're actually doing two statements at once.0292

Now, you see, if we do Foods, there are two elements in the Array.0302

We can compare--Foods, Fruits--and they both have the same elements.0309

But if, on the Foods, I create a new Array, now it has a different reference.0315

So, when I do the print, right there, you will notice that the Foods is empty, and the Fruits still has the two elements.0322

This one here--the array.new--this is just the empty Array; that is what it points to now.0345

Now, as you just saw, when we create a new object, we use the constructor.0360

That is what we are going to talk about next: this .new method.0366

We can create new objects, and we are working with a reference, because we are not actually building the object; we are working with references every time we're programming.0370

Here, we are going to allocate memory for the new object.0380

Then, we invoke the initialize method.0386

When you call that new, there is no new method in the class: so it is actually using a class called Initialize.0390

So, for this myfirstclass.new, this one is going to look at your method initialize.0399

Let's see a live example of that in action.0422

This goes into the myfirstclass, and I get it substantiated with new; and notice that there are zero arguments here.0426

I'm going to exit here, and I'm going to go to an .rb file called myfirstclass.0438

We are going to create that class and show you a live example of the initialize statement.0451

I'm CamelCaseing it here...here is my Initialize...and we'll just call it Value...and let's do something to print out what that value is.0460

We have our class, Myfirstclass--when you call that new method, it is going to pass the value into Initialize.0483

Notice, we are requiring a parameter here now.0496

I can just do IRB...I'm going to require that class.0504

Let's go run the example.0513

Now, I'm going to show you something: notice, it says argument...wrong number of arguments is 0 for 1.0518

The reason for that is, in my constructor, I actually specify "I need to put one argument in there."0527

Let's do that again.0534

I'm just going to put in a value--I'll put FooBar in.0540

Next, I can call my other method that returns it--and it prints out FooBar.0547

That is an example of the .new method in action.0559

Notice, for this example, we had a parameter val.0568

Over here, we passed in that FooBar method.0578

Next thing--we will just go really quickly about this--there is garbage collection in Ruby.0592

When an object is no longer needed, it will automatically be destroyed.0598

"No longer needed" equals it's no longer reachable.0607

If there is no way to access that object reference anymore, it's going to go away--it's going to be garbage-collected--if there is no way to access it.0611

That is why--so you have to be careful with this: global values will always be reachable if the Ruby Interpreter is running.0621

If it's a global value, it's always reachable.0629

You would have to release it--release that value, the reference it's pointing to, to get rid of it.0632

Otherwise, it is always going to stay there.0639

So, with global values, I would recommend you be careful.0641

You don't want to end up having a bunch of different values that are running globally and using up all your memory, so definitely be careful with global values.0652

The next thing we are going to talk about is object identity.0666

Every object has an object identifier; what we use for that is this object_id method.0670

This keeps every single object unique for the lifetime of the program.0680

Usually, when you call this array.new, this object_id, you will get some huge number afterwards that is the object ID; so, if you call array.new, object_id, you will get a big number for it.0691

Let's show you an example here.0705

Let's just try a bunch of different things; I'll do string.new, array.new, and let's do even another string.new.0713

We have all of these...three objects here; now we just call a.object_id; notice, we get some ID value.0727

As I get the object ID--same for the Array; notice the value is different; and, for the C, the string is actually the same--it's an empty string--but you will notice that it also has a unique object identifier.0738

As you see, every object ID here is constant and unique for the lifetime of the program.0765

The next thing we want to talk about is object class.0779

The class method will determine the class of the object.0785

By taking any object, you can specify this class method, and it will tell you what object this belongs to.0791

You can also use the superclass method, and it will determine the parent class.0801

Here is the example we have: we have this string; we are going to allocate a new string object with the value Newstring.0810

After we allocate it, we call this object method class, and it will get us this value String.0821

Also, notice that we can call superclass even to Object.0832

Object has its own parent class, too.0836

Object' superclass, its parent, is BasicObject.0843

Now, if you call this BasicObject's superclass, there is no object above it.0850

If I were to take basicobject.superclass, it would just return nil.0856

Next, we want to go on through object testing.0884

The first thing we will use in object testing is the instance_of method.0890

The instance_of method checks the class of the object.0897

You will notice it here: we use our same string, Newstring, and I can say, "Is this string an instance of String?"0903

In this case, it is, so it will say true.0915

Again, you could also have used parentheses here--I didn't use them.0919

There is another method we could do to test what the object is.0923

This is the is_a method.0929

The is_a method tests the class and its superclasses.0931

Remember, string is part of the String class, but the String class also belongs to the Object class.0938

If I call string.is_a?(object), because that is one of the parent classes to it, it returns true.0953

Also, notice this === method also is true.0962

If I do string.is_a?(string), it will return true; if I do string.is_a?(basicobject), it will also return true.0970

The next method we are going to look at is the respond_to method.0985

This method allows you to test if you can invoke a method.0992

This might be useful if I'm coding something and I'm agnostic to what the object is.0997

Some of them might have this method; some might not.1007

By using this respond_to, I can check, "Hey, does it have this method?" before I start processing it and calling this method.1010

For example, let's say I have an Array, and I want to clear that Array: so I want to say, "Hey, does this respond to the clear method?", and this one says it's true, so it does.1017

There are also other methods that have it; you will see it in the Hashes, too--Hashes have a clear method.1030

You can do the exact same thing: if I have a Hash, let's say I do hash.new(h), I can just do h.respond_to?, and I can pass in the clear, and see if it does have it or not.1043

The next object testing we are going to look at is the equal tilde.1074

The equal tilde, by default, returns false.1083

But you will see that there are some Ruby class objects that do use it.1087

The string and the regular expression use it for pattern matching.1091

So, if we have this value, abc123, I'm saying, "Hey, I want to do a regular expression, and tell me, in the string itself, does it contain a digit?"1099

I'm trying to match a digit in this one.1113

You will notice that, to match a digit, I'm using this whole expression here.1124

That is going to return me 4.1134

4 is saying where in this string index it found the first digit, and that is what it returns me.1137

If you start at 4, a is 0,1,2,3,4...so this value, 1, is in the fourth index place.1145

This is actually the index value.1157

If you are creating your own classes, you can actually define this equal tilde to what is needed for your class.1166

Again, you should use it for some type of similarity matching.1180

If, for regular expressions, you want to look for some kind of object, and match something, kind of like a needle in a haystack, this is what this equal tilde would be useful for.1185

The next one we are looking at is this less than, equal, greater than value.1202

What this value does is, it is used for comparing two object instances of the same class.1209

That means, if you have two instances, you compare equal, less than the other, or greater than the other.1218

If it's equal, it's going to just give you a 0.1229

If it's less than the other value--let's say, for example, I have a value on the left side that is less than the value on the right side--so let's say, for example, a is less than b; if a is less than b, it is going to turn back a 1.1237

If a is greater than b, it will return a -1.1265

So, if it's a negative value, the negative value says the left value is bigger; if it's a positive number, it's saying the right value is bigger.1282

A negative value...negative equals left value is greater.1296

And a positive value...again, this is -1, and this is a 1...this means the right value is greater.1313

And if they are equal, it will just be zero.1334

Let's go through a few examples of this.1338

Here, we have the value 1, and we are comparing it with another object, the value 2.1343

This is going to return back 1--why does it return back 1?--because this is a bigger value than the one on the left, so the right one wins in this case.1351

This value...we have a value 5 at the beginning, and we're comparing it to value 1; notice, it is -1: the one on the left wins.1365

Here, we have a value where we are comparing 5 with 5; it's the same, so it's 0; so it's equal.1376

It is equal in this case.1384

We can go through a live example of this, too.1391

Let me show you, so we can get a better feel for it.1401

We can use the IRB again.1407

Let's go ahead and just use our string.new; what I am going to show you is an example with the string object.1411

Because it uses alphabetical ordering to define which is greater...1425

First, let me show you some of the examples that we went through for these slides.1432

First, if I do instance_of, pass in string, you will see it returns true.1438

Then, let's do the respond_to method, and it responds true too, so string also has a clear method.1446

Now, let's go ahead and show you the string: so, we have our mynewstring, and I'm going to use that comparison value with the letter a.1457

Notice that it returns the value 1 for this case.1467

Now, let's do that again, but this time with a z.1474

This time, it returns a -1; so, in the first case, the left side is mynewstring, and in the next case, we used the z, and it returns -1.1479

Let's do something else: what if we just pass a with z...let's see what we get.1501

For this example, the first one is winning with the letter a, which is interesting, because you would think that the later letter would win.1509

If I pass another one, if I pass more letters to that, it still says the first one is winning, just because it only looks at the first letter.1522

That's that comparison.1541

Now let's look at object equality.1546

There are many ways to compare objects.1550

This way...we are going to look at the equal method.1555

What this does is, it checks if they refer to the same object.1561

You might get confused...it uses equal for other reasons...but just use it for checking the object; don't use it to check the values in these objects, if those are identical...this just checks if object a has the same object ID as object b.1567

Look at this example: we have a=100; then we have b=100; these both have the same value, but they are different objects.1583

Notice, when we call this a.equal? b, it returns false.1615

But look, if I make a new value called c=b, it is looking at the same object reference; so c.equal? b will return true.1621

The next object equality method we are going to look at is ==.1636

We are also going to be looking at this not equal, which is the opposite of it.1643

Again, let's use our example: a=100, b=100; a==b does equal true in this case; it's looking at the strings ==method, and it says, "Hey, this value inside--that is the one I want you to check for ==," so it returns true.1648

And not equal is just the exact opposite, so it's not true--it will be false in this case.1674

a!=b will return true, though, if I took a value like...100 is not equal to 101.1680

I do 100!=101; this would return true.1694

Let's look at object equality for Arrays.1710

We are going to look at an example where they have the same number of elements and the elements are equal.1715

Both of them have 3 elements in A and B, and they have the exact same values that match up.1725

For this case, notice, when we call a==b, it returns true because it matches both these cases here.1736

We have three of them on both, and these three values are the same.1745

That is how the Array uses the == method.1758

But if you call this object_id, not equal to object_id, this will also return true, since they are different objects.1762

The next object equality method we are going to look at is the Hash.1780

The Hash--what it does for equality is, it checks if they have the same number of key-value pairs, and the second thing it looks for is that the keys and values are all equal.1785

Notice that this value is the same--1,1,2,2,3,3, for the key, and the value is 2,3 here.1804

So, a.equals? b is true.1816

But let's say I were to make a change: instead of 3 here, I change this to 4--I update it like that.1819

Now, if I call a.equals? b, it would return false.1832

The next equality method we are looking at is ===.1847

If this hasn't been defined, it's going to default to just ==.1856

If it hasn't been defined, you should define it on your own, but if it isn't, it is going to just say, "Hey, you have an == method; that is the one I am going to use."1867

How do objects utilize it? The class tests if an object is an instance of that class.1875

So, for that example here, look at this string--we have this string class, and it's going to say === abc.1883

Now, abc is an instance of that class, so it will return true for that case.1895

If we look at this example, the Range tests if it belongs in that Range.1904

Again, this is an ===.1910

Since, out of this range from 1 to 100, does that 50 belong in that Range of 1 to 100? It does, so this will also return true.1918

Let's check out how symbols utilize it.1941

The symbol tests if that symbol is the same--and if that is, it's true--or if it's a string with the same text.1944

We already know that if I do Educator === to the same symbol, Educator, it's going to be equal.1955

If I even took a symbol a===a, that would be true.1965

But, in this case, I actually tell it, "Hey, if it has a string with the same text as a symbol, that also is going to return true."1976

This also returns true in that case.1986

For this next part, we are going to look at object conversion.1991

Ruby allows objects to be converted to a different class.1999

It has two ways of doing this.2005

One way is with this explicit conversion, and another way is through implicit conversion.2008

Explicit conversion is something you kind of force it into, whereas implicit is kind of more implied.2016

Let's see it in action so it will make more sense.2025

First, we are going to look at this explicit conversion.2029

Like I said, it is used to force a conversion to another representation.2033

Some methods that do this...you have this to_s that converts it to a string, to_i converts it to an integer, to_f to a float...2039

Let's say I take a value, 5--I can do to_f, and that will convert it to 5.00.2051

to_a will convert to an Array, to_c converts it to a complex value, and to_r converts it to a rational value.2065

You can try this with many of the popular ones--Arrays, Hashes, Strings, Integer values--and you will notice that some have these conversion methods already in them that allow you to do it; others don't.2076

Here is the other way: you can use implicit conversion.2096

Implicit conversion is used more for comparisons and conversions.2100

These are other methods that have to be defined to do implicit conversion.2107

You have your to_array, your to_str, your to_int, and your to_hash.2116

Let's look at an example: what we're going to look at is this class called FooBar.2130

We have both examples: we have our explicit conversion method, and then we have our implicit conversion method.2138

Let's open our terminal so we can take a look at this.2163

Let's see if I have the object here...I do not, so let's go back and take a look here...2178

We're going to call FooBar...one is lowercase; the other is uppercase.2196

I'm actually going to create this class in the IRB.2207

I'm going to make the class foobar...my explicit one will be lowercase...and I'm going to make my to_str in uppercase.2210

OK, so I have my foobar object here.2224

First, let's substantiate it with f=foobar.new.2229

Let's show an example of these two cases.2237

For the example one, I'm just going to put value f, and it returns the explicit version.2241

What happens here...it's doing interpolation on the f, so it calls the to_str, this value foobar.2256

But another way is--watch--if I do value, and I do +f; it's all caps this time.2264

This is using the implicit conversion.2275

So, depending on which way you code, you will notice that it's not using the same method.2278

When you are creating your objects, you have to think about this and develop for these reasons.2286

That is conversion.2298

Now, let's look at the Kernel module.2303

The Kernel module allows you to do object conversion, also.2307

There are some methods that allow it.2312

First, you have your Array, and this allows you to do conversions to_ary and to_a.2318

For this, it will convert to_ary or it will convert to_a, depending on the circumstances.2332

If it's to_ary, but let's say it's not defined or it returns nil, then it will use to_a.2344

This will be used if it's not defined or it returns nil.2355

Now, for the Float, this converts the argument to Fixnum or Bignum.2365

Number types are converted directly.2374

You will notice that these are all actually functions that are built in the Kernel module.2378

Then you have this Integer, which will convert arguments to Fixnum or Bignum, and number types are converted directly.2389

We also have a String function that will convert the argument to a string by calling the to_s method.2401

Notice how these functions will do conversions, but they use different methods to do them.2410

The Array one uses to_ary and to_a, but the String uses just to_s to do that; versus the Integer, that will take your value and convert it to Fixnum or Bignum, depending on what is passed in.2417

Let's see it in action.2430

First, you can use these in any order; these are global conversion methods.2434

First, let's look at Array: if I pass Array, the value 5, it creates an Array just with that value; so if you pass this Array function, a value, it's just going to creat a new Array with that value in it.2440

Let's try Float...if I pass 5 into Float, though, notice, it takes this value that is an Integer, but it actually converts it to a Float using the to_f function...so if I do 5.to_f, it does the same thing.2456

If I pass Integer, the value 5, it's just going to call it by itself; it's already an Integer.2478

And if I just do String, it's just going to return the string value for that, also.2490

Again, this is just using the to_s, so it's just creating a new object of itself.2498

The next thing we are going to look at is object conversion using coerce.2518

This is used for mixed-type numeric operations.2524

It is intended to find a common type between two operants.2531

You will see here, what we have is 1.2--we have a Float value here.2540

And 3--we have our Integer.2551

Notice, what it does is, when I pass this Float, and I say, "Hey, I'm going to call this method coerce, and I'm going to pass you this argument 3," I want this value 3 to have a compatible type with the Float object.2559

It's going to say, "Hey, with this Float object with the coerce, make this 3 so it's friendly, so I can work with it."2577

What it returns is the Float value of 3, which is 3.0.2584

Here is our original value, 1.2, that called the coerce object.2592

Now, this is also a Float here.2604

Let's go through an example so you can get a better idea...2610

Let's see...I thought I created some code here, but let's go ahead and create a new piece called coerce.rb.2621

Actually, no, I do have it here.2635

I have a file called point.rb, so what we do here is, I have this object called Point, notice the constructor: I have this Initialize takesone value; it initializes that to a point in this class.2639

There is another method called coerce; other is the value that gets passed in, so I'm saying, with this method I'm creating, it can take one value--which is the way you should be defining coerce.2660

Then, I have this case statement; it says, "OK, with this value other, when it's a numeric value, I want to convert that to a Float."2681

What it will do is, it's going to return an Array, with a Float and the initial value, which is that point.2696

This will return a converted numeric value, which will become a Float, and you get your initial value, which is that point.2708

So, this will look, actually, like this; else, it's going to say, "Hey, I'm going to throw an error, because I can't handle this type."2727

My coerce method only allows me to work with this Numeric type, so I'm going to just say, "Else, erase the type error; tell it 'This can't be coerced into this other that class.'" This other that class is whatever class is in there.2741

In the future, I could use this point value and say, if it's a string, maybe I want to go ahead and try to convert that...to coerce it into my point value.2760

But I'm not there yet, so I'm only handling the numeric case.2772

Let's go ahead and try it out.2777

I'm going to require my Point class, so I have my Point object now, and I'm going to just work with 2, and I'm going to say...I need to substantiate point.new...I'm going to pass 5 in here, and then I'm going to do 2+p.2780

Notice how, even though I have this Integer value, 5, I do 2+p, and it converts it to 7.0.2810

It's using that coerce method that I defined to convert that to a Float, so what it's doing is, that p is becoming 2+5.0.2822

Since that is a Float, this is another step that Ruby is doing; it's changing that 2 into a Float, too.2835

It's saying 2.0 and 5.0.2843

So, that's coerce; you can see a little different trick of how it is being used there.2855

The next object conversion we are going to look at is Boolean.2860

We know True and False are distinct objects.2865

Both do not have a conversion method, though.2872

Object conversion...but both of them don't have a conversion method...what am I talking about? I'll get to that.2878

However, every object does have a Boolean value.2883

If I have this object that is not false, nor nil, it is treated as true.2888

You could think, whatever object I'm using, if it's not false or nil, it's going to be true.2896

If I use this method here, if I am not nil--which is, if I even pass in the value 0, it's going to print my value; if I pass you a string with a, 0, 1, these all will print this value.2906

Let me show you a better example, though.2928

Let's go back to our IRB.2930

What I'm going to do here is, I'm going to create a method called whatbooleanvalueami.2935

I'm going to check both--if the object is equal to nil, or if object is equal to false, I want it to return the False string.2945

Otherwise, I want it to return the True string.2958

Let's try some different values for this, now.2966

Whatbooleanvalueami...so I pass a 0...oh, I forgot to define the argument, so let's start again.2969

I'm going to put this object...it's pulling that up...0...the number 0 returns true; 1 also returns true; strings return true; but if I return nil, it's false, and false also returns false.2982

I can try...math, pi here; that also returns true; so if I take any of these objects--let's say I'm making my if statement--and I'm going to say 'hello world', and if I run if0, it will print 'hello world' with that.3015

The next thing we're going to go over is object copying.3047

To do this, we have two methods.3051

You have this dup method, which copies tainted objects--only tainted objects.3054

And then we have this clone method, which is able to copy both frozen and tainted objects.3061

It copies singleton methods, and it is meant to be overridden to do deep copies.3069

Both the dupe and the clone create shallow copies by default.3076

The reason I say, in the clone, that it is meant to be overridden to do deep copies--dup usually does a level 1 copy, but clone--you can get even deeper by how you define it.3081

Let's go back to our example.3098

Let's see...let me show you some in action.3104

Let's say I have my Array, two elements, and I create a new one using the dup method.3110

Now, when you print x and y, notice they both are the same; they both have the same values.3124

Let's do this now: let's put in a value, 3, into x.3131

Now let's check out our y value.3137

Notice the y value still doesn't have the value 3 in it; it's doing a level 1 array copy with this dup, and it's a shallow copy, so 3 is not in there--but if you look at the x value, 3 is in there.3141

Let's do an example of how we can define this with a clone, because by default, clone is also going to do a shallow copy, but let's instead define the object to do that, and then we can make a deep copy of that.3162

To do that, I have an example that we can use: this is basket.rb example.3180

This class has a constructor with fruits and vegetables.3188

It uses the attributes accessor to define @fruits and @vegetables.3198

But what's interesting is, I have this clone method here.3207

It will tell basket.new that I am going to do a deep clone copy with self.fruits.clone and self.vegetables.clone.3210

Before we do that, I am going to put here 'deep clone copy', but let's not even define that at the beginning; let's just try it without it.3226

I also have this method called show_all; it will print all the different fruits and vegetables that are in this basket.3238

First, I am not going to do the clone method; let's see how that works.3249

If I do this basket.rb...and I create my new basket.new...I'm going to define two Arrays, fruits and vegetables, so I have my fruits, and I'm going to do my vegetables...3255

And then I'm going to create a new one using this clone method, so I have a and b.3279

Now, I'm going to call this show_all--we have our fruits and vegetables--and then I'm going to do the same with our new value--with a.3285

They are both the same.3294

Plus, if I do object_id, they are also unique; they are both different objects.3296

What is interesting, though, is: if you do this vegetables.object_id, and then the b one, notice they have the same value to it.3310

So, if I pass into the value b...I'm going to add another vegetable into here...I'm going to add some broccoli...so now, if I do show_all, notice a actually has the vegetable 'broccoli', too.3324

And, if I do b, it also has the same value.3344

It's because they are using the same object, because it's a shallow copy.3348

Let's do it again, but this time, we're going to define the value.3351

What I'm going to do here is...here I've added it back in, and we are going to do the exact same thing here.3359

Apples...carrots...and let me define that as b again...oops, I forgot to require my class...now, I'm going to do our deep clone copy.3375

And again, I'm going to do my vegetables--I'm going to put some broccoli in there.3399

If I do b.show_all--and let's also check out the object_id--and now I'm going to do a.show_all...notice, the 'vegetables' in a doesn't contain broccoli.3406

But also notice that the object ID has also changed.3421

Here is the example with deep clone that we have done.3430

Deep clone method...so you see, by default, both of them are doing the shallow copies, but clone--we have overridden it to do deep copies.3434

The next one we will look at is object freezing.3453

Frozen objects are immutable; you can't change them.3457

The internal states cannot be changed, and any mutator methods you use will fail.3463

If you try to change it, it will not work.3474

Here is an example: we have our fruits example: we have array[apple, banana, grapes].3475

I say to the Array that I want to call my freeze method; next, I ask it, using this method called frozen?, so it says, "Hey, is it frozen?"--in this case, it says true, because I called freeze beforehand.3483

Now, I'm going to try to use a mutator method; I'm going to add pear into it.3500

But my result will say, "This is a runtime error; you can't modify a frozen Array."3506

The next one we are going to look at is object marshalling.3518

There are two different states when you do marshalling.3523

There is a save state and a load state.3526

With the save state, you call marshal.dump and your object.3531

That will serialize the object and all descendant objects, and it is going to save that state--serialized.3538

Then, you can take that returned object and you can call on it marshal.load, and that will return that serialized data back into your Ruby object.3550

Let's see an example of that in action.3565

Again, I am going to run my IRB.3570

I have a function I want to show you that I have been using--I mean a class: this class called MyWord: it has one constructor called Initialize; it takes one value, word, and the word variable gets passed.3578

I have another method called shout; it's going to take that word and shout it with an exclamation point.3600

I'm going to require that in my method, and I'm going to substantiate that with hello, so I have my MyWord object.3608

And now, I'm going to do a dump; so it's going to serialize this.3627

I'm going to put data=marshal.dump; it's going to get the whole object and serialize it; notice, it knows we have that here.3632

I'm going to take that data and load it.3646

I'm going to do obj=marshal.load(data), and there we go: we have our object again.3650

Let's check if they are the same ID, though--so we'll have this o.object_id...856510...and then our new serialized one...they are actually different object IDs.3660

They aren't the same; that is interesting.3675

Let's go ahead and try to shout it; it says 'hello!', and then I use the o, and it also has the same value.3678

So, it's not the same object, but the element, the value, is the same inside it.3689

That is object marshalling.3703

Next, we are going to look at tainted objects.3707

This uses the method taint; it marks the object as tainted, and it's used for untrusted user input or an unreliable source.3711

What is an unreliable source? Maybe it came from a form-fill off the Internet.3725

This is some value that wasn't in our system before; it came from an external source that...we don't know where it came from; it could have been anyone.3736

We could say this is a tainted value.3749

For example, let's say we have something that looks like user input...so I want to pass in this value: lorem ipsum 123.3752

Now, I don't know who that source is, so I'm going to mark it as 'taint'.3761

That is going to say that the object is tainted.3767

Later in my code, let's say that I have this process that says, "OK, is this object tainted?"--it says it's true: yes, it is.3770

When I know it's true, then I can run other validations.3779

I can make another...I can put my code here and run validations if it's tainted.3782

What you would want to do, usually, is if it's tainted, you can run some type of validations--else, if it isn't, you can do something else.3789

I run my validations; let's say they all return true--everything is valid, there is nothing bad about it--then I can call this userinput.untaint, which will mark it as untainted again.3813

Then, let's say--it's not tainted anymore--I want to do another check; I can check, "Is it tainted?", and if it isn't, I can continue to the next process.3829

The last one we are going to look at is untrusted objects.3844

This is new in Ruby 1.9.3849

First, you have this trust method; this marks the object as trusted because it came from a trusted or untrusted source.3852

Then, you have another method called untrust.3866

If it's trusted, you can clear it up with untrust; and then you have this untrusted, which is more like a reader attribute for that.3874

Now, all these...this whole trust, untrust, trusted...these are all part of the security model for Ruby.3884

It's still fairly now, and you can use this to...how necessary, but if you mark it as trusted or untrusted, Ruby might have some library set say, "Hey, if this is an untrusted source, maybe I don't want to run the code this way."3896

I recommend you look more into the Ruby security model to see how it will fit in your code, if you...I recommend to use this.3915

Otherwise...we have gone through a lot of different methods in Object; we have gone through equality, conversion, coercion...3927

That is the end of this course.3939

I hope to see you next time at Educator.com.3943

Educator®

Please sign in to participate in this lecture discussion.

Resetting Your Password?
OR

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Membership Overview

  • Available 24/7. Unlimited Access to Our Entire Library.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lecture slides for taking notes.
  • Track your course viewing progress.
  • Accessible anytime, anywhere with our Android and iOS apps.