Enter your Sign on user name and password.

Forgot password?
Sign In | Subscribe
Start learning today, and be successful in your academic & professional career. Start Today!

Use Chrome browser to play professor video
Justin Mui

Justin Mui

Methods: Part 1

Slide Duration:

Table of Contents

I. 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
  • 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!

Methods: Part 1

  • A method provides a way to gather statements and expressions into one area
  • It can be used repeatedly to execute a specific task
  • It can be defined to do all sorts of tasks
  • The return keyword forces a return to the end of the method
  • Any value following the return value will also be returned
  • The method undef allows you to undefine instance methods
  • Method names should begin with a lowercase letter
  • When longer than a word, it should be separated with underscores
  • A method name with a question mark answers the question posed by the method
  • Usually it returns true or false
  • A method name with an exclamation point is usually a mutator method
  • The exclamation point means to use it with caution
  • Method aliases allow you to define a new name to an existing method
  • Operator methods can be defined in your own class
  • Methods can be associated with code blocks
  • The method block_given? will return true if a block is passed

Methods: Part 1

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

Transcription: Methods: Part 1

Hi! Welcome back to Educator.com.0000

Today's lesson is on Methods, Part 1.0002

What is a method? It provides a way to gather statements and expressions into one area.0009

It can be used repeatedly to execute a specific task.0020

Methods can be defined to do all sorts of tasks.0026

You will definitely be using methods quite often; you have seen a bunch of methods already in a lot of previous lessons we've done.0035

The goal of this lesson is to get you very, very understanding of all the basics of a method so, going forward, it clears a lot of questions you will have.0043

Let's first look at a very basic method that you will commonly see.0055

Parts of a basic method: you will see parameters--notice, for this one, it only has one parameter; in this case, there is just one parameter.0062

You will also notice, for this method, it takes one parameter, but it also has a default value; that default value for that parameter is 0.0079

Quite often, in other languages, they have to overload the function to do this type of behavior, but only Ruby has this default parameter set up.0096

There is a return value, and depending on what is in the parameter, it will return different things.0113

That is another thing you have--a return value.0129

Notice that this method doesn't have the word 'return' that you will often see; since this is the last statement, these will be returned, though.0136

If I pass hello_world without any parameters, it will default n to 0, and that means it will display "Hi!".0153

If n is greater than 1, it will print out "Hello worlds!"; if it's equal to 1, it will print out "Hello world!"; and else, it will do "Hi!".0170

You will see here, as I called the method, hello_world, there are 0 parameters, and it just prints out "Hi!".0181

You will notice that this is the return value, and that is a string.0195

Again, I could also pass hello_world, and if I pass in 2, it would give me "Hello worlds!".0204

If I could also--notice, I didn't put parentheses there--but if I also did hello_world, and I passed in 1, it would return to me "Hello world!".0227

You will also notice that the actual name uses an underscore; quite often in Ruby, you will see underscores for all the methods: you will not see CamelCase.0252

This is just normal convention in Ruby.0267

OK, let's go to the next one.0273

We just saw three different return values; let's look further into this return value.0276

You can actually explicitly write return; when you do that, this return keyword forces a return to the end of the method.0285

If you put anything below it, it's not going to get to it--it's just going to return after it sees this keyword--so that is a very important keyword.0297

Also, any value that is following that return value will also be returned.0307

If I pass in a String after that return, an Integer, whatever object I pass--it's going to be returned with it.0313

Return and whatever object this is...and this object can be anything.0323

It can be a String; it can be an Integer, a Float, an object you created...0330

Most often, you won't see any return value in the code.0346

Usually, it's omitted when it's not required, as you saw in that basic method--it didn't have any return values.0354

It's already the last statement at the end; it's already going to be returned, anyway; so there is no reason to explicitly tell it.0361

Let's go through some examples where you will see it.0370

Right here, I have a factorial example; this will give you the factorial, depending on the parameter put in.0375

See here, our method factorial takes one argument; it returns 1 if you pass y=0.0384

Notice that it just returns: that means that it ignores this next line; so if y=0, it's going to ignore this line over here, but if it is 1 or greater, then it's going to call this method here.0395

This method actually calls itself; so, if I did 3, it would do 3 times factorial...and 3-1, we have a 2, and after that, it calls factorial of 2...that will get you 2...times factorial 1.0413

Here is where we get that 1; this is going to break down, 1 times factorial 0, and notice, when it hits 0, it sees that over here: it says, "OK, that y value is equal to 0--I'm just going to return 1."--so that is 1.0453

Now that we have broken down what all the different factorials are, here is what it gets when I pass factorial 3--remember, this is for factorial 3: when I do that, it's going to do 3 times 2 times 1 times 1, and we get, at the end, 6.0476

Let's go through some code of this example; I want to show you what you can do without the return value, too.0511

We have our terminal here; let's first specify the method.0525

Again, I'm putting one parameter there: I'm going to return 1 if that y=0, but instead of having that second return value--it's not needed, since it's the last line of this method--I'm not going to do it.0531

I'm just going to put return, y times factorial, y minus 1, and then I'm just going to end it.0548

Let's see it in action: if I do factorial 0, I get 1; factorial 1, I get 1 also; 2--that is 2 times 1--I get 2; 3--which is 3 times 2 times 1--6; 4--we get 24; and 5--120.0562

Notice, we didn't even have to use that return value.0593

That is our factorial example.0601

Now, Ruby allows you to return two values; you must explicitly set that return value in this case.0604

If you are returning two values, you have to explicitly set the return.0617

That return value is collected, and it's returned as an Array.0624

We have an example here: I have this method called square_it; it takes two arguments, and those two arguments you pass in--it's going to take them to the power of 2 and just return it.0631

Notice, on my return value, I actually didn't put any parentheses, and it allows that.0646

I have the comma, and my 'to the power of 2' there...so if I call square_it and pass in my two values, my return is an Array of 4 and 25.0655

It's going to take 2 squared and 5 squared and put that into an Array.0671

The next thing I want to talk about is undefining methods.0682

You probably won't use this too often, but it's still useful to know, because there will come a time when you will need it, and it's good to know it.0688

To do this, the key action value is undef: you call that and the method you want to undefine, and it will make that disappear.0699

This takes one parameter, an identifier that specifies the method name.0716

It works in classes to undefine instance methods.0722

So, if you are in a class, and you are going to undefine these instance methods, you can also undefine the inherited methods.0727

For those previous examples, if I do undef(square_it), undef(factorial), it does not exist anymore; if I call those functions again, it's just going to give me an error.0735

I can actually go to the terminal...and we still have the factorial in memory, so if I do factorial(5), I get 120.0748

Now, if I call undef(factorial), and then I call it again, now it says "NameError: undefined local variable or method 'factorial' for main:Object" since I have created this method in the global scope.0757

The next thing we want to look at is method names.0781

Method names should begin with a lowercase letter, unlike classes that still use that CamelCasing.0787

When longer than a word, separate the words with an underscore: that is key.0802

Maybe in another language, you see this HelloWorld; it follows this CamelCase convention; but in Ruby, when you are creating methods, this is the way to go.0811

It's going to say hello_world; it spaces the two words out, and it uses underscores to do that.0830

The next thing I want to talk about is...you will see methods with an equals sign after them, a question mark, and an exclamation point.0843

We have our equals sign here, and our exclamation point, and our question mark.0852

First, let's just look at the equals sign.0860

Equals sign means the method is a setter and that it can be invoked using an assignment syntax.0863

Follow these rules: if you are creating a method with an equals sign, that means that method is a setter.0870

Now, let's look at methods with question marks.0883

When the method name has a question mark at the end, this means it answers the question posed by the method.0890

Usually, it returns a Boolean value, true or false; sometimes, instead of false, you will get nil.0900

For example, let's just look at the empty? method--it's 'empty?'--it has a question mark at the end.0911

You know that it is contained in a wide variety of objects: so, in Array, if an Array has no elements, it will return true.0920

It's also defined in the String object; so, if a String has 0 characters, it will return true.0934

And, of course, you can create your own empty? method for your own objects, and you can define them yourself with what you need it to do--what does empty mean in your object?0944

The next thing is to look at method names with exclamation points--an exclamation point at the end.0960

Usually, these methods are mutators; that is the common thing.0970

What is a mutator? A mutator alters the state of an object.0979

This exclamation point will actually change the existing object, in most cases.0987

You will also see other methods that don't use exclamation points, and they still change the object--like delete.0995

So, why the exclamation point--why do you put it in? The exclamation point means to use it with caution.1002

This is the significance of that exclamation point.1011

It's going to change the object; it might do something else, but an exclamation point means, "Be careful when you use this!"1019

For example, I have this Numbers--it has three elements in this array.1028

I'm calling this sort!--notice I have that exclamation point.1035

That will actually change this existing object here, and it's going to sort that.1040

This Numbers object now has been changed to be an Array of three elements, but sorted to be [1, 2, 3].1049

Remember, if I didn't have that exclamation point--I just called sort--it would create a new object; it wouldn't modify the existing object.1064

That one is just Numbers.sort.1071

Just remember, with the exclamation point, you have to be more cautious.1076

OK, let's look at method aliases next.1083

This defines a new name for an existing method.1089

With a method alias, you can give a method another name, and you can use both of them.1095

It's not uncommon to have more than one name, so it's not a problem, and Ruby makes it really easy to do this.1109

The key here is this keyword called alias.1117

What you do is...the first parameter you put in is the new method you want to give it.1124

What is the new name you want to give this method?1134

Then, you need to pass in the existing method's name.1139

It takes those three elements.1145

So, you have to pass alias, the new method name you want to give it, and the existing method name that it is right now.1149

Very simple example: we have this method called hi_world--it returns "Hi"--and I want to give it another method name, an alias.1159

I'm going to call alias and pass in the new method hello_world, and the existing method hi_world.1171

Now, when I call hello_world, it will return me that value "Hi"--just as if I called hi_world, it will return that value "Hi" to me.1180

Next, let's look at operator methods.1196

Operators can be defined in your own class.1200

The Array operators, the square bracket and the square bracket equal, can take any number of arguments.1206

These operators are quite different from other ones you will see.1221

If you look at unary operators, they take no arguments at all.1228

Binary operators are passed on argument, so they operate on self and the argument.1235

Examples of a binary operator are plus, minus, multiplication...1245

Example here: if I have the plus operator, I call define, put + and the other argument; and then I can go ahead and put my code here and end it.1252

That is very, very basic; let's get deeper with how this works, with this binary operator.1273

I'm going to create a class and have a couple of these binary methods in there.1283

Here is my class: let's call it SuperClass; I have a constructor that takes one String value...and now, I'm going to actually create my binary operator.1295

I do my addition; I say it's going to take a parameter called other_value; and this will actually update this value that is in this object.1311

It's going to append the other value to that string.1324

Then, I'm going to make another one with a minus sign.1333

This will do the exact opposite: whatever that other_value is, it's going to remove it from the string.1336

To do that in my code, I'm going to use a method called gsub; it's going to update the value in place.1342

I'm going to pass Regexp here, so it's going to first look for that other_value, look for any spaces around that value, remove any spaces around it...and then, it's going to return it as that value.1356

OK, it looks like I actually missed the multiplication sign...1381

Let's try that again...let's see if I can grab...no...OK, I'm going to define that again.1393

Again, I'm just creating my constructor, and I'm going to make my other_value.1411

Notice, I can also use interpolation here: since I'm not worrying about that right now--I'm just showing the method--I'm not going to do anything of that sort.1425

Here is my regular expression; it's going to remove other_value.1439

Make sure I got that right...1452

OK, so, I have my object, my SuperClass, done.1458

The first thing we're going to do is initialize it.1463

I've created my object; my constructor created a value called SuperString in this object.1471

Now, I'm going to show you, live, that binary operator in action.1478

If I take my object, and I do at...and I'm going to say it's SuperString, but it has 'goop' in it now...so SC plus that string value...it's going to use this operator here...and the return value is 'SuperString with goop', which is my new value in that object.1483

The same thing--I can subtract it out, so if I do SC minus 'goop', notice it removes that whole word.1510

So, now it's 'SuperString with'; that doesn't sound that good, so I want to remove that 'with', also.1519

Now, it says 'SuperString'; let's say 'with SuperOperators', since we have the new binary operators.1526

There you go: 'SuperString with SuperOperators'.1534

That is a case with all the different binary operators in it, and it works!1539

The next thing we're going to look at is methods and parentheses.1559

In most cases, parentheses are optional; it's more on your programming...what you like better: do you like parentheses or not?1566

Parentheses are optional in most cases.1580

If you have this puts method, you will notice that a lot of times I don't use parentheses with it, but with parentheses--they both work the same way.1588

They will both print out 'hello world' at the end.1597

You can also just print a string called 'hello world'.1603

I have this value 'Hi', and when I call the link method, which is part of this string, it will return me the number of characters.1611

But notice, I can return it with parentheses or none; both of them will still work.1620

There are cases where it is required, though, so let's go over those.1632

The main one is method invocations with more than one argument; this is a case where it is required.1637

For example, I have a method that takes two arguments; if I don't put these parentheses, it's going to show me a warning that says, "That's not proper; I don't know if it's being used for a method or something else."1647

So, you always want to add the parentheses in this case.1664

The last thing I want to go over is methods and blocks.1674

When you define a method, you can also pass a block in there.1681

You can use yield, and it will pass that value into the block you gave it.1687

Methods can be associated with blocks.1695

There is a value called block_given?; this returns true if a block is passed.1701

Using that, you can do different processes in this method.1711

Yield will call the block within the method.1715

So this block--now, using this yield command, you can actually tell it when to call it.1719

I have this method called processor: it takes one value, a number value.1725

Now, if a block is given, I'm going to say, "Process it using that block; I don't know what that is, but process it with it--you must know what you want to process it for if you have the block there; else, I'm going to process it myself."1735

I'm just going to multiply whatever that parameter is by itself; so it's num squared.1750

Let's go for a little example of how the block is used.1757

I'm going to create that processor that takes that parameter num; "If block is given, go ahead and process it using it; else, go ahead and just square it up."1764

If I just do processor(2), it returns me 4; I'm processing it now.1785

Now, let's go ahead and do it this time with 2 again, but this time let's pass in a value--let's say I want to do that argument and add 5 to it.1796

This returns 7 now; it uses the block I did, and we passed in 2, so it's 2+5.1814

I can do this with other values, too--I pass 10 in there, and then just do x times 2, and it says 20 instead of 10 times 10, which is 100.1822

I can change that to minus, and notice I return 8.1838

I can change the parameter, too, and it will return a different value.1846

That is the methods and blocks; that is actually the last thing I wanted to go over for this methods lesson, in Part 1.1857

Join me in the second lesson, where we go over deeper parts in the methods, and give you a better feel of all the different pieces to it.1867

Until then, see you next time at Educator.com!1880

Educator®

Please sign in for full access to this lesson.

Sign-InORCreate Account

Enter your Sign-on user name and password.

Forgot password?

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.

Use this form or mail us to .

For support articles click here.