Ruby
The programming language
that made Rails possible
The Oath
The Oath
“I do solemnly swear:
I will not consider this an exhaustive Ruby lesson
and I will study Ruby more as I progress...
irb
The secret weapon of the Rubyists
The REPL
The REPL

Ruby comes with a Read-Eval-Print-Loop tool called irb
The REPL

Ruby comes with a Read-Eval-Print-Loop tool called irb
  In short, you feed it some Ruby and it prints results
The REPL

Ruby comes with a Read-Eval-Print-Loop tool called irb
  In short, you feed it some Ruby and it prints results
T...
The REPL

Ruby comes with a Read-Eval-Print-Loop tool called irb
  In short, you feed it some Ruby and it prints results
T...
The REPL

Ruby comes with a Read-Eval-Print-Loop tool called irb
  In short, you feed it some Ruby and it prints results
T...
Using irb
Using irb

            $ irb
            >> 1 + 2
            => 3
            >> "james".capitalize
            => "James...
Using irb
 Run irb to launch it
                        $ irb
                        >> 1 + 2
                        => ...
Using irb
 Run irb to launch it
                        $ irb
 You enter Ruby         >> 1 + 2
 expressions            => ...
Using irb
 Run irb to launch it
                         $ irb
 You enter Ruby          >> 1 + 2
 expressions             ...
Using irb
 Run irb to launch it
                           $ irb
 You enter Ruby            >> 1 + 2
 expressions         ...
Using irb
 Run irb to launch it
                           $ irb
 You enter Ruby            >> 1 + 2
 expressions         ...
Data Types
The building blocks of Ruby
Data Types and Structures
Data Types and Structures
Ruby has data types common to most programming
languages: String, Integer, Float, …
Data Types and Structures
Ruby has data types common to most programming
languages: String, Integer, Float, …
Ruby has two...
Data Types and Structures
Ruby has data types common to most programming
languages: String, Integer, Float, …
Ruby has two...
Data Types and Structures
Ruby has data types common to most programming
languages: String, Integer, Float, …
Ruby has two...
Data Types and Structures
Ruby has data types common to most programming
languages: String, Integer, Float, …
Ruby has two...
String    “ta lot of escapesn#{1 + 2}”   ‘less ( or ’)’
                      255              0377
Integer
              ...
String    “ta lot of escapesn#{1 + 2}”   ‘less ( or ’)’
                      255              0377
Integer
              ...
String    “ta lot of escapesn#{1 + 2}”   ‘less ( or ’)’
                      255              0377
Integer
              ...
String    “ta lot of escapesn#{1 + 2}”   ‘less ( or ’)’
                      255              0377
Integer
              ...
String    “ta lot of escapesn#{1 + 2}”   ‘less ( or ’)’
                      255              0377
Integer
              ...
String    “ta lot of escapesn#{1 + 2}”   ‘less ( or ’)’
                      255              0377
Integer
              ...
String    “ta lot of escapesn#{1 + 2}”   ‘less ( or ’)’
                      255              0377
Integer
              ...
String    “ta lot of escapesn#{1 + 2}”   ‘less ( or ’)’
                      255              0377
Integer
              ...
Working With Strings
Working With Strings
               >>   space = "textra space n"
               =>   "textra space n"
               >>  ...
Working With Strings
                   >>   space = "textra space n"
String provides:   =>
                   >>
        ...
Working With Strings
                   >>   space = "textra space n"
String provides:   =>
                   >>
        ...
Working With Strings
                         >>   space = "textra space n"
String provides:         =>
                  ...
Working With Strings
                         >>   space = "textra space n"
String provides:         =>
                  ...
Working With Strings
                         >>   space = "textra space n"
String provides:         =>
                  ...
Working With Strings
                         >>   space = "textra space n"
String provides:         =>
                  ...
Working With Arrays
Working With Arrays
                >>   a = [0, 1]
                =>   [0, 1]
                >>   a << 2 << 3 << 4
    ...
Working With Arrays
                  >>   a = [0, 1]
Array provides:   =>
                  >>
                       [0,...
Working With Arrays
                    >>   a = [0, 1]
Array provides:     =>
                    >>
                    ...
Working With Arrays
                      >>   a = [0, 1]
Array provides:       =>
                      >>
              ...
Working With Arrays
                      >>   a = [0, 1]
Array provides:       =>
                      >>
              ...
Working With Arrays
                      >>   a = [0, 1]
Array provides:       =>
                      >>
              ...
Working With Arrays
                      >>   a = [0, 1]
Array provides:       =>
                      >>
              ...
Working With Hashes
Working With Hashes
               >>   h = {:a => 1, :b => 2}
               =>   {:a=>1, :b=>2}
               >>   h[:b...
Working With Hashes
                 >>   h = {:a => 1, :b => 2}
Hash provides:   =>
                 >>
                 ...
Working With Hashes
                      >>   h = {:a => 1, :b => 2}
Hash provides:        =>
                      >>
  ...
Working With Hashes
                         >>   h = {:a => 1, :b => 2}
Hash provides:           =>
                     ...
Working With Hashes
                         >>   h = {:a => 1, :b => 2}
Hash provides:           =>
                     ...
Working With Hashes
                         >>   h = {:a => 1, :b => 2}
Hash provides:           =>
                     ...
Working With Hashes
                         >>   h = {:a => 1, :b => 2}
Hash provides:           =>
                     ...
Type Conversions
Type Conversions
              >>   pi = "3.1415"
              =>   "3.1415"
              >>   pi.to_f
              => ...
Type Conversions
Ruby has many        >>   pi = "3.1415"
                     =>   "3.1415"
conversion methods   >>   pi.t...
Type Conversions
Ruby has many          >>   pi = "3.1415"
                       =>   "3.1415"
conversion methods     >> ...
Type Conversions
Ruby has many            >>   pi = "3.1415"
                         =>   "3.1415"
conversion methods    ...
Type Conversions
Ruby has many            >>   pi = "3.1415"
                         =>   "3.1415"
conversion methods    ...
Type Conversions
Ruby has many            >>   pi = "3.1415"
                         =>   "3.1415"
conversion methods    ...
Flow Control
Conditional logic
The if statement
The if statement

                   num = rand(10)
                   print "#{num}: "
                   if num == 7
   ...
The if statement
 Ruby has if/elsif/else
 conditionals             num = rand(10)
                          print "#{num}:...
The if statement
 Ruby has if/elsif/else
 conditionals             num = rand(10)
                          print "#{num}:...
The if statement
 Ruby has if/elsif/else
 conditionals               num = rand(10)
                            print "#{n...
The if statement
 Ruby has if/elsif/else
 conditionals               num = rand(10)
                            print "#{n...
When Things go Wrong
When Things go Wrong


              >> 42 / 0
              ZeroDivisionError: divided by 0
               from (irb):1:i...
When Things go Wrong
Ruby “raises” errors
(called Exceptions)
when things go wrong
                       >> 42 / 0
      ...
When Things go Wrong
Ruby “raises” errors
(called Exceptions)
when things go wrong
Error objects have a   >> 42 / 0
      ...
When Things go Wrong
Ruby “raises” errors
(called Exceptions)
when things go wrong
Error objects have a   >> 42 / 0
      ...
When Things go Wrong
Ruby “raises” errors
(called Exceptions)
when things go wrong
Error objects have a   >> 42 / 0
      ...
When Things go Wrong
Ruby “raises” errors
(called Exceptions)
when things go wrong
Error objects have a       >> 42 / 0
  ...
Exception Handling
Exception Handling


              >>   begin
              >>     n = 42 / 0
              >>   rescue ZeroDivisionError ...
Exception Handling

Put code that might
raise errors between   >>   begin
                       >>     n = 42 / 0
begin …...
Exception Handling

Put code that might
raise errors between      >>   begin
                          >>     n = 42 / 0
b...
Objects and Methods
In Ruby, very nearly everything is an object
Everything is an Object
Everything is an Object


                >> -42.abs
                => 42
                >> 3.times { puts "Howdy" }
   ...
Everything is an Object

 With a few very minor
 exceptions, everything   >> -42.abs
                          => 42
 in R...
Everything is an Object

 With a few very minor
 exceptions, everything     >> -42.abs
                            => 42
 ...
Instance Variables
Private, per object storage
class Name
 def initialize(first = nil)
   self.first = first
 end

 def first=(first)
  @first = first
 end

 def first
  @first
 ...
class Name
 def initialize(first = nil)
   self.first = first
 end

 def first=(first)
  @first = first
 end

 def first
  @first
 ...
class Name
 def initialize(first = nil)
   self.first = first
 end

 def first=(first)
  @first = first
 end

 def first
  @first
 ...
class Name
 def initialize(first = nil)
   self.first = first
 end

 def first=(first)
  @first = first
 end

 def first
  @first
 ...
class Name
 def initialize(first = nil)
   self.first = first
 end

 def first=(first)
  @first = first
 end

 def first
  @first
 ...
class Name
 def initialize(first = nil)
   self.first = first
 end

 def first=(first)
  @first = first
 end

 def first
  @first
 ...
class Name
 def initialize(first = nil)
   self.first = first
 end                          dana     = Name.new("Dana")
     ...
class Name
 def initialize(first = nil)
   self.first = first
 end                          dana     = Name.new("Dana")
     ...
class Name
 def initialize(first = nil)
   self.first = first
 end                          dana     = Name.new("Dana")
     ...
class Name
 def initialize(first = nil)
   self.first = first
 end                          dana     = Name.new("Dana")
     ...
Single Inheritance
Single Inheritance
                class Parent
                 def greet
                   @greeting ||= "Hello!"
     ...
Single Inheritance
 A Class can declare   class Parent
                        def greet
 one parent               @greeti...
Single Inheritance
 A Class can declare    class Parent
                         def greet
 one parent                @gre...
Single Inheritance
 A Class can declare      class Parent
                           def greet
 one parent                ...
Questions and
Dangerous Methods
Questions and
Dangerous Methods
                >>   0.zero?
                =>   true
                >>   0.0.zero?
    ...
Questions and
Dangerous Methods
Ruby has some   >>
                =>
                     0.zero?
                     tr...
Questions and
Dangerous Methods
Ruby has some        >>
                     =>
                          0.zero?
        ...
Questions and
Dangerous Methods
Ruby has some        >>
                     =>
                          0.zero?
        ...
“Mixins”
A uniquely Ruby way to share methods
Modules
Modules
          module Netstring
           def to_netstring(*args)
            str = to_s(*args)
            "#{str.len...
Modules
                       module Netstring
                        def to_netstring(*args)
Ruby doesn’t have        s...
Modules
                          module Netstring
                           def to_netstring(*args)
Ruby doesn’t have   ...
Modules
                          module Netstring
                           def to_netstring(*args)
Ruby doesn’t have   ...
Modules
                          module Netstring
                           def to_netstring(*args)
Ruby doesn’t have   ...
Blocks and Iterators
Rubyists turn their noses up at loops
Blocks
Blocks

         def until_successful
          loop do
            break if yield == :success
          end
         end
...
Blocks
In Ruby, you can pass    def until_successful
a block (some code) to    loop do
                            break i...
Blocks
In Ruby, you can pass    def until_successful
a block (some code) to    loop do
                            break i...
Blocks
In Ruby, you can pass    def until_successful
a block (some code) to    loop do
                            break i...
for (…; …; …) {

}
for (…; …; …) {

                }




Rubyists Don’t “Loop”
We “iterate” instead
The each() Iterator
The each() Iterator


                name = %w[James Edward Gray II]
                name.each do |word|
                ...
The each() Iterator

 Let Ruby manage   name = %w[James Edward Gray II]
 indexes for you   name.each do |word|
           ...
The each() Iterator

 Let Ruby manage          name = %w[James Edward Gray II]
 indexes for you          name.each do |wor...
The map() Iterator
The map() Iterator


                nums = *1..5
                p nums
                p nums.map { |n| n ** 2 }
       ...
The map() Iterator
 map() is used to
 transform your
 collection
                    nums = *1..5
                    p nu...
The map() Iterator
 map() is used to
 transform your
 collection
                           nums = *1..5
 Each item of the...
The map() Iterator
 map() is used to
 transform your
 collection
                           nums = *1..5
 Each item of the...
The select() Iterator
The select() Iterator


                 nums = *1..10
                 p nums
                 p nums.select { |n| n % 2 ...
The select() Iterator

 select() can be used
 to filter a collection

                         nums = *1..10
              ...
The select() Iterator

 select() can be used
 to filter a collection
 Each item is passed         nums = *1..10

 into the ...
The select() Iterator

 select() can be used
 to filter a collection
 Each item is passed         nums = *1..10

 into the ...
And Much, Much More!
I have barely scratched the surface of Ruby
Ruby is a Rich Language
Ruby is a Rich Language
Over 140 methods on String and over 70 on Array
Ruby is a Rich Language
Over 140 methods on String and over 70 on Array
Automatic “big math” conversions
Ruby is a Rich Language
Over 140 methods on String and over 70 on Array
Automatic “big math” conversions
A very capable ca...
Ruby is a Rich Language
Over 140 methods on String and over 70 on Array
Automatic “big math” conversions
A very capable ca...
Ruby is a Rich Language
Over 140 methods on String and over 70 on Array
Automatic “big math” conversions
A very capable ca...
Ruby is a Rich Language
Over 140 methods on String and over 70 on Array
Automatic “big math” conversions
A very capable ca...
Questions?
Learning Ruby
from Ruby Lab
Your book has instructions on how to use irb to
learn more about Ruby from the language itself
Ruby
Ruby
Upcoming SlideShare
Loading in...5
×

Ruby

925

Published on

This was the second speech of a three day Rails training I gave in Tulsa, OK in the spring 2010.

Published in: Technology
1 Comment
3 Likes
Statistics
Notes
  • ruby , rails
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Views
Total Views
925
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
54
Comments
1
Likes
3
Embeds 0
No embeds

No notes for slide








































































































































































































  • Ruby

    1. 1. Ruby The programming language that made Rails possible
    2. 2. The Oath
    3. 3. The Oath “I do solemnly swear: I will not consider this an exhaustive Ruby lesson and I will study Ruby more as I progress in Rails, so James will not come take my keyboard away!”
    4. 4. irb The secret weapon of the Rubyists
    5. 5. The REPL
    6. 6. The REPL Ruby comes with a Read-Eval-Print-Loop tool called irb
    7. 7. The REPL Ruby comes with a Read-Eval-Print-Loop tool called irb In short, you feed it some Ruby and it prints results
    8. 8. The REPL Ruby comes with a Read-Eval-Print-Loop tool called irb In short, you feed it some Ruby and it prints results This is an excellent way to learn the language
    9. 9. The REPL Ruby comes with a Read-Eval-Print-Loop tool called irb In short, you feed it some Ruby and it prints results This is an excellent way to learn the language It becomes a powerful data management tool when used with Rails
    10. 10. The REPL Ruby comes with a Read-Eval-Print-Loop tool called irb In short, you feed it some Ruby and it prints results This is an excellent way to learn the language It becomes a powerful data management tool when used with Rails Do yourself a favor and start playing with irb a lot
    11. 11. Using irb
    12. 12. Using irb $ irb >> 1 + 2 => 3 >> "james".capitalize => "James" >> %w[y b u R].reverse => ["R", "u", "b", "y"] >> _.join("-") => "R-u-b-y" >> exit
    13. 13. Using irb Run irb to launch it $ irb >> 1 + 2 => 3 >> "james".capitalize => "James" >> %w[y b u R].reverse => ["R", "u", "b", "y"] >> _.join("-") => "R-u-b-y" >> exit
    14. 14. Using irb Run irb to launch it $ irb You enter Ruby >> 1 + 2 expressions => 3 >> "james".capitalize => "James" >> %w[y b u R].reverse => ["R", "u", "b", "y"] >> _.join("-") => "R-u-b-y" >> exit
    15. 15. Using irb Run irb to launch it $ irb You enter Ruby >> 1 + 2 expressions => 3 >> "james".capitalize => "James" irb responds with the >> %w[y b u R].reverse results as you type => ["R", "u", "b", "y"] >> _.join("-") => "R-u-b-y" >> exit
    16. 16. Using irb Run irb to launch it $ irb You enter Ruby >> 1 + 2 expressions => 3 >> "james".capitalize => "James" irb responds with the >> %w[y b u R].reverse results as you type => ["R", "u", "b", "y"] >> _.join("-") => "R-u-b-y" _ holds the last result >> exit
    17. 17. Using irb Run irb to launch it $ irb You enter Ruby >> 1 + 2 expressions => 3 >> "james".capitalize => "James" irb responds with the >> %w[y b u R].reverse results as you type => ["R", "u", "b", "y"] >> _.join("-") => "R-u-b-y" _ holds the last result >> exit Use exit() to quit
    18. 18. Data Types The building blocks of Ruby
    19. 19. Data Types and Structures
    20. 20. Data Types and Structures Ruby has data types common to most programming languages: String, Integer, Float, …
    21. 21. Data Types and Structures Ruby has data types common to most programming languages: String, Integer, Float, … Ruby has two primary data structures: Array and Hash
    22. 22. Data Types and Structures Ruby has data types common to most programming languages: String, Integer, Float, … Ruby has two primary data structures: Array and Hash These structures are very versatile and can serve as sets, queues, stacks, …
    23. 23. Data Types and Structures Ruby has data types common to most programming languages: String, Integer, Float, … Ruby has two primary data structures: Array and Hash These structures are very versatile and can serve as sets, queues, stacks, … Ruby has some other data types, like Time
    24. 24. Data Types and Structures Ruby has data types common to most programming languages: String, Integer, Float, … Ruby has two primary data structures: Array and Hash These structures are very versatile and can serve as sets, queues, stacks, … Ruby has some other data types, like Time All of the above are full objects in Ruby
    25. 25. String “ta lot of escapesn#{1 + 2}” ‘less ( or ’)’ 255 0377 Integer 0xFF 0b11111111 0.00003 Float 3.0e-5 [“James”, “Edward”, “Gray”, “II”] Array %w[James Edward Gray II] Hash {“name” => “James”, “age” => 33} Symbol :first_name Regexp /AJ(?:ames )?E(?:dward )?G(?:ray )?(?:II|2)z/ Time.now Time Time.local(2010, 3, 10) Time.utc(2010, 3, 10)
    26. 26. String “ta lot of escapesn#{1 + 2}” ‘less ( or ’)’ 255 0377 Integer 0xFF 0b11111111 0.00003 Float 3.0e-5 [“James”, “Edward”, “Gray”, “II”] Array %w[James Edward Gray II] Hash {“name” => “James”, “age” => 33} Symbol :first_name Regexp /AJ(?:ames )?E(?:dward )?G(?:ray )?(?:II|2)z/ Time.now Time Time.local(2010, 3, 10) Time.utc(2010, 3, 10)
    27. 27. String “ta lot of escapesn#{1 + 2}” ‘less ( or ’)’ 255 0377 Integer 0xFF 0b11111111 0.00003 Float 3.0e-5 [“James”, “Edward”, “Gray”, “II”] Array %w[James Edward Gray II] Hash {“name” => “James”, “age” => 33} Symbol :first_name Regexp /AJ(?:ames )?E(?:dward )?G(?:ray )?(?:II|2)z/ Time.now Time Time.local(2010, 3, 10) Time.utc(2010, 3, 10)
    28. 28. String “ta lot of escapesn#{1 + 2}” ‘less ( or ’)’ 255 0377 Integer 0xFF 0b11111111 0.00003 Float 3.0e-5 [“James”, “Edward”, “Gray”, “II”] Array %w[James Edward Gray II] Hash {“name” => “James”, “age” => 33} Symbol :first_name Regexp /AJ(?:ames )?E(?:dward )?G(?:ray )?(?:II|2)z/ Time.now Time Time.local(2010, 3, 10) Time.utc(2010, 3, 10)
    29. 29. String “ta lot of escapesn#{1 + 2}” ‘less ( or ’)’ 255 0377 Integer 0xFF 0b11111111 0.00003 Float 3.0e-5 [“James”, “Edward”, “Gray”, “II”] Array %w[James Edward Gray II] Hash {“name” => “James”, “age” => 33} Symbol :first_name Regexp /AJ(?:ames )?E(?:dward )?G(?:ray )?(?:II|2)z/ Time.now Time Time.local(2010, 3, 10) Time.utc(2010, 3, 10)
    30. 30. String “ta lot of escapesn#{1 + 2}” ‘less ( or ’)’ 255 0377 Integer 0xFF 0b11111111 0.00003 Float 3.0e-5 [“James”, “Edward”, “Gray”, “II”] Array %w[James Edward Gray II] Hash {“name” => “James”, “age” => 33} Symbol :first_name Regexp /AJ(?:ames )?E(?:dward )?G(?:ray )?(?:II|2)z/ Time.now Time Time.local(2010, 3, 10) Time.utc(2010, 3, 10)
    31. 31. String “ta lot of escapesn#{1 + 2}” ‘less ( or ’)’ 255 0377 Integer 0xFF 0b11111111 0.00003 Float 3.0e-5 [“James”, “Edward”, “Gray”, “II”] Array %w[James Edward Gray II] Hash {“name” => “James”, “age” => 33} Symbol :first_name Regexp /AJ(?:ames )?E(?:dward )?G(?:ray )?(?:II|2)z/ Time.now Time Time.local(2010, 3, 10) Time.utc(2010, 3, 10)
    32. 32. String “ta lot of escapesn#{1 + 2}” ‘less ( or ’)’ 255 0377 Integer 0xFF 0b11111111 0.00003 Float 3.0e-5 [“James”, “Edward”, “Gray”, “II”] Array %w[James Edward Gray II] Hash {“name” => “James”, “age” => 33} Symbol :first_name Regexp /AJ(?:ames )?E(?:dward )?G(?:ray )?(?:II|2)z/ Time.now Time Time.local(2010, 3, 10) Time.utc(2010, 3, 10)
    33. 33. Working With Strings
    34. 34. Working With Strings >> space = "textra space n" => "textra space n" >> space.strip => "extra space" >> space.rstrip => "textra space" >> "James".delete("aeiou") => "Jms" >> date = "March 2010" => "March 2010" >> date[0..4] => "March" >> date[-2..-1] => "10" >> date[/d+/] => "2010"
    35. 35. Working With Strings >> space = "textra space n" String provides: => >> "textra space n" space.strip => "extra space" >> space.rstrip => "textra space" >> "James".delete("aeiou") => "Jms" >> date = "March 2010" => "March 2010" >> date[0..4] => "March" >> date[-2..-1] => "10" >> date[/d+/] => "2010"
    36. 36. Working With Strings >> space = "textra space n" String provides: => >> "textra space n" space.strip => "extra space" Case changing >> => space.rstrip "textra space" >> "James".delete("aeiou") => "Jms" >> date = "March 2010" => "March 2010" >> date[0..4] => "March" >> date[-2..-1] => "10" >> date[/d+/] => "2010"
    37. 37. Working With Strings >> space = "textra space n" String provides: => >> "textra space n" space.strip => "extra space" Case changing >> => space.rstrip "textra space" Whitespace stripping >> "James".delete("aeiou") => "Jms" >> date = "March 2010" => "March 2010" >> date[0..4] => "March" >> date[-2..-1] => "10" >> date[/d+/] => "2010"
    38. 38. Working With Strings >> space = "textra space n" String provides: => >> "textra space n" space.strip => "extra space" Case changing >> => space.rstrip "textra space" Whitespace stripping >> "James".delete("aeiou") => "Jms" General editing >> => date = "March 2010" "March 2010" >> date[0..4] => "March" >> date[-2..-1] => "10" >> date[/d+/] => "2010"
    39. 39. Working With Strings >> space = "textra space n" String provides: => >> "textra space n" space.strip => "extra space" Case changing >> => space.rstrip "textra space" Whitespace stripping >> "James".delete("aeiou") => "Jms" General editing >> => date = "March 2010" "March 2010" >> date[0..4] Indexing => "March" >> date[-2..-1] => "10" >> date[/d+/] => "2010"
    40. 40. Working With Strings >> space = "textra space n" String provides: => >> "textra space n" space.strip => "extra space" Case changing >> => space.rstrip "textra space" Whitespace stripping >> "James".delete("aeiou") => "Jms" General editing >> => date = "March 2010" "March 2010" >> date[0..4] Indexing => "March" >> date[-2..-1] => "10" … >> date[/d+/] => "2010"
    41. 41. Working With Arrays
    42. 42. Working With Arrays >> a = [0, 1] => [0, 1] >> a << 2 << 3 << 4 => [0, 1, 2, 3, 4] >> a.pop => 4 >> a => [0, 1, 2, 3] >> a[1] => 1 >> a[1..-1] => [1, 2, 3] >> a & [0, 2, 4, 6] => [0, 2] >> a | [42] => [0, 1, 2, 3, 42]
    43. 43. Working With Arrays >> a = [0, 1] Array provides: => >> [0, 1] a << 2 << 3 << 4 => [0, 1, 2, 3, 4] >> a.pop => 4 >> a => [0, 1, 2, 3] >> a[1] => 1 >> a[1..-1] => [1, 2, 3] >> a & [0, 2, 4, 6] => [0, 2] >> a | [42] => [0, 1, 2, 3, 42]
    44. 44. Working With Arrays >> a = [0, 1] Array provides: => >> [0, 1] a << 2 << 3 << 4 => [0, 1, 2, 3, 4] Adding elements >> => a.pop 4 >> a => [0, 1, 2, 3] >> a[1] => 1 >> a[1..-1] => [1, 2, 3] >> a & [0, 2, 4, 6] => [0, 2] >> a | [42] => [0, 1, 2, 3, 42]
    45. 45. Working With Arrays >> a = [0, 1] Array provides: => >> [0, 1] a << 2 << 3 << 4 => [0, 1, 2, 3, 4] Adding elements >> => a.pop 4 >> a Removing elements => [0, 1, 2, 3] >> a[1] => 1 >> a[1..-1] => [1, 2, 3] >> a & [0, 2, 4, 6] => [0, 2] >> a | [42] => [0, 1, 2, 3, 42]
    46. 46. Working With Arrays >> a = [0, 1] Array provides: => >> [0, 1] a << 2 << 3 << 4 => [0, 1, 2, 3, 4] Adding elements >> => a.pop 4 >> a Removing elements => [0, 1, 2, 3] >> a[1] Indexing => >> 1 a[1..-1] => [1, 2, 3] >> a & [0, 2, 4, 6] => [0, 2] >> a | [42] => [0, 1, 2, 3, 42]
    47. 47. Working With Arrays >> a = [0, 1] Array provides: => >> [0, 1] a << 2 << 3 << 4 => [0, 1, 2, 3, 4] Adding elements >> => a.pop 4 >> a Removing elements => [0, 1, 2, 3] >> a[1] Indexing => >> 1 a[1..-1] => [1, 2, 3] Set operations >> a & [0, 2, 4, 6] => [0, 2] >> a | [42] => [0, 1, 2, 3, 42]
    48. 48. Working With Arrays >> a = [0, 1] Array provides: => >> [0, 1] a << 2 << 3 << 4 => [0, 1, 2, 3, 4] Adding elements >> => a.pop 4 >> a Removing elements => [0, 1, 2, 3] >> a[1] Indexing => >> 1 a[1..-1] => [1, 2, 3] Set operations >> a & [0, 2, 4, 6] => [0, 2] … >> a | [42] => [0, 1, 2, 3, 42]
    49. 49. Working With Hashes
    50. 50. Working With Hashes >> h = {:a => 1, :b => 2} => {:a=>1, :b=>2} >> h[:b] => 2 >> h[:c] = 3 => 3 >> h => {:a=>1, :b=>2, :c=>3} >> h.keys => [:a, :b, :c] >> h.values => [1, 2, 3] >> h.include? :c => true >> h.include? :d => false
    51. 51. Working With Hashes >> h = {:a => 1, :b => 2} Hash provides: => >> {:a=>1, :b=>2} h[:b] => 2 >> h[:c] = 3 => 3 >> h => {:a=>1, :b=>2, :c=>3} >> h.keys => [:a, :b, :c] >> h.values => [1, 2, 3] >> h.include? :c => true >> h.include? :d => false
    52. 52. Working With Hashes >> h = {:a => 1, :b => 2} Hash provides: => >> {:a=>1, :b=>2} h[:b] => 2 Key-value storage >> => h[:c] = 3 3 >> h => {:a=>1, :b=>2, :c=>3} >> h.keys => [:a, :b, :c] >> h.values => [1, 2, 3] >> h.include? :c => true >> h.include? :d => false
    53. 53. Working With Hashes >> h = {:a => 1, :b => 2} Hash provides: => >> {:a=>1, :b=>2} h[:b] => 2 Key-value storage >> => h[:c] = 3 3 >> h Key addition/removal => {:a=>1, :b=>2, :c=>3} >> h.keys => [:a, :b, :c] >> h.values => [1, 2, 3] >> h.include? :c => true >> h.include? :d => false
    54. 54. Working With Hashes >> h = {:a => 1, :b => 2} Hash provides: => >> {:a=>1, :b=>2} h[:b] => 2 Key-value storage >> => h[:c] = 3 3 >> h Key addition/removal => {:a=>1, :b=>2, :c=>3} >> h.keys Indexing => >> [:a, :b, :c] h.values => [1, 2, 3] >> h.include? :c => true >> h.include? :d => false
    55. 55. Working With Hashes >> h = {:a => 1, :b => 2} Hash provides: => >> {:a=>1, :b=>2} h[:b] => 2 Key-value storage >> => h[:c] = 3 3 >> h Key addition/removal => {:a=>1, :b=>2, :c=>3} >> h.keys Indexing => >> [:a, :b, :c] h.values => [1, 2, 3] Queries >> h.include? :c => true >> h.include? :d => false
    56. 56. Working With Hashes >> h = {:a => 1, :b => 2} Hash provides: => >> {:a=>1, :b=>2} h[:b] => 2 Key-value storage >> => h[:c] = 3 3 >> h Key addition/removal => {:a=>1, :b=>2, :c=>3} >> h.keys Indexing => >> [:a, :b, :c] h.values => [1, 2, 3] Queries >> h.include? :c => true … >> h.include? :d => false
    57. 57. Type Conversions
    58. 58. Type Conversions >> pi = "3.1415" => "3.1415" >> pi.to_f => 3.1415 >> pi.to_i => 3 >> num = 42 => 42 >> num.to_s => "42" >> num.to_s(16) => "2a" >> animals = "chickens,cows,Rubyists" => "chickens,cows,Rubyists" >> animals.split(",") => ["chickens", "cows", "Rubyists"] >> animals.split(",", 2) => ["chickens", "cows,Rubyists"] >> animals.split(",").join(" | ") => "chickens | cows | Rubyists"
    59. 59. Type Conversions Ruby has many >> pi = "3.1415" => "3.1415" conversion methods >> pi.to_f => 3.1415 >> pi.to_i => 3 >> num = 42 => 42 >> num.to_s => "42" >> num.to_s(16) => "2a" >> animals = "chickens,cows,Rubyists" => "chickens,cows,Rubyists" >> animals.split(",") => ["chickens", "cows", "Rubyists"] >> animals.split(",", 2) => ["chickens", "cows,Rubyists"] >> animals.split(",").join(" | ") => "chickens | cows | Rubyists"
    60. 60. Type Conversions Ruby has many >> pi = "3.1415" => "3.1415" conversion methods >> pi.to_f => 3.1415 >> pi.to_i Strings can become => 3 Integers or Floats >> => num = 42 42 >> num.to_s => "42" >> num.to_s(16) => "2a" >> animals = "chickens,cows,Rubyists" => "chickens,cows,Rubyists" >> animals.split(",") => ["chickens", "cows", "Rubyists"] >> animals.split(",", 2) => ["chickens", "cows,Rubyists"] >> animals.split(",").join(" | ") => "chickens | cows | Rubyists"
    61. 61. Type Conversions Ruby has many >> pi = "3.1415" => "3.1415" conversion methods >> pi.to_f => 3.1415 >> pi.to_i Strings can become => 3 Integers or Floats >> => num = 42 42 >> num.to_s => "42" Numbers can >> num.to_s(16) => "2a" Stringified in a base >> animals = "chickens,cows,Rubyists" => "chickens,cows,Rubyists" >> animals.split(",") => ["chickens", "cows", "Rubyists"] >> animals.split(",", 2) => ["chickens", "cows,Rubyists"] >> animals.split(",").join(" | ") => "chickens | cows | Rubyists"
    62. 62. Type Conversions Ruby has many >> pi = "3.1415" => "3.1415" conversion methods >> pi.to_f => 3.1415 >> pi.to_i Strings can become => 3 Integers or Floats >> => num = 42 42 >> num.to_s => "42" Numbers can >> num.to_s(16) => "2a" Stringified in a base >> animals = "chickens,cows,Rubyists" => "chickens,cows,Rubyists" Strings become >> => animals.split(",") ["chickens", "cows", "Rubyists"] Arrays, and go back >> => animals.split(",", 2) ["chickens", "cows,Rubyists"] >> animals.split(",").join(" | ") => "chickens | cows | Rubyists"
    63. 63. Type Conversions Ruby has many >> pi = "3.1415" => "3.1415" conversion methods >> pi.to_f => 3.1415 >> pi.to_i Strings can become => 3 Integers or Floats >> => num = 42 42 >> num.to_s => "42" Numbers can >> num.to_s(16) => "2a" Stringified in a base >> animals = "chickens,cows,Rubyists" => "chickens,cows,Rubyists" Strings become >> => animals.split(",") ["chickens", "cows", "Rubyists"] Arrays, and go back >> => animals.split(",", 2) ["chickens", "cows,Rubyists"] >> animals.split(",").join(" | ") => "chickens | cows | Rubyists" …
    64. 64. Flow Control Conditional logic
    65. 65. The if statement
    66. 66. The if statement num = rand(10) print "#{num}: " if num == 7 puts "Lucky!" elsif num <= 3 puts "A little low." else puts "A boring number." end # >> 2: A little low.
    67. 67. The if statement Ruby has if/elsif/else conditionals num = rand(10) print "#{num}: " if num == 7 puts "Lucky!" elsif num <= 3 puts "A little low." else puts "A boring number." end # >> 2: A little low.
    68. 68. The if statement Ruby has if/elsif/else conditionals num = rand(10) print "#{num}: " The code is run if the if num == 7 puts "Lucky!" condition is true elsif num <= 3 puts "A little low." else puts "A boring number." end # >> 2: A little low.
    69. 69. The if statement Ruby has if/elsif/else conditionals num = rand(10) print "#{num}: " The code is run if the if num == 7 puts "Lucky!" condition is true elsif num <= 3 puts "A little low." In Ruby, false and nil else puts "A boring number." are false and all other end # >> 2: A little low. objects are true (0, “”, etc.)
    70. 70. The if statement Ruby has if/elsif/else conditionals num = rand(10) print "#{num}: " The code is run if the if num == 7 puts "Lucky!" condition is true elsif num <= 3 puts "A little low." In Ruby, false and nil else puts "A boring number." are false and all other end # >> 2: A little low. objects are true (0, “”, etc.)
    71. 71. When Things go Wrong
    72. 72. When Things go Wrong >> 42 / 0 ZeroDivisionError: divided by 0 from (irb):1:in `/' from (irb):1 from :0
    73. 73. When Things go Wrong Ruby “raises” errors (called Exceptions) when things go wrong >> 42 / 0 ZeroDivisionError: divided by 0 from (irb):1:in `/' from (irb):1 from :0
    74. 74. When Things go Wrong Ruby “raises” errors (called Exceptions) when things go wrong Error objects have a >> 42 / 0 ZeroDivisionError: divided by 0 type, message, and from (irb):1:in `/' from (irb):1 backtrace from :0
    75. 75. When Things go Wrong Ruby “raises” errors (called Exceptions) when things go wrong Error objects have a >> 42 / 0 ZeroDivisionError: divided by 0 type, message, and from (irb):1:in `/' from (irb):1 backtrace from :0
    76. 76. When Things go Wrong Ruby “raises” errors (called Exceptions) when things go wrong Error objects have a >> 42 / 0 ZeroDivisionError: divided by 0 type, message, and from (irb):1:in `/' from (irb):1 backtrace from :0
    77. 77. When Things go Wrong Ruby “raises” errors (called Exceptions) when things go wrong Error objects have a >> 42 / 0 ZeroDivisionError: divided by 0 type, message, and from (irb):1:in `/' from (irb):1 backtrace from :0 By default, processing stops if the error isn’t “rescued”
    78. 78. Exception Handling
    79. 79. Exception Handling >> begin >> n = 42 / 0 >> rescue ZeroDivisionError => error >> n=0 >> end => 0 >> n => 0
    80. 80. Exception Handling Put code that might raise errors between >> begin >> n = 42 / 0 begin … end >> >> rescue ZeroDivisionError => error n=0 >> end => 0 >> n => 0
    81. 81. Exception Handling Put code that might raise errors between >> begin >> n = 42 / 0 begin … end >> >> rescue ZeroDivisionError => error n=0 >> end Add rescue clauses => >> 0 n for the error types you => 0 want to handle
    82. 82. Objects and Methods In Ruby, very nearly everything is an object
    83. 83. Everything is an Object
    84. 84. Everything is an Object >> -42.abs => 42 >> 3.times { puts "Howdy" } Howdy Howdy Howdy => 3
    85. 85. Everything is an Object With a few very minor exceptions, everything >> -42.abs => 42 in Ruby is an Object >> 3.times { puts "Howdy" } Howdy Howdy Howdy => 3
    86. 86. Everything is an Object With a few very minor exceptions, everything >> -42.abs => 42 in Ruby is an Object >> 3.times { puts "Howdy" } Howdy Howdy Even a number literal is Howdy an Object and you can => 3 call methods on it
    87. 87. Instance Variables Private, per object storage
    88. 88. class Name def initialize(first = nil) self.first = first end def first=(first) @first = first end def first @first end end Instance Variables Private, per object storage
    89. 89. class Name def initialize(first = nil) self.first = first end def first=(first) @first = first end def first @first end end Instance Variables Private, per object storage
    90. 90. class Name def initialize(first = nil) self.first = first end def first=(first) @first = first end def first @first end end Instance Variables Private, per object storage
    91. 91. class Name def initialize(first = nil) self.first = first end def first=(first) @first = first end def first @first end end Instance Variables Private, per object storage
    92. 92. class Name def initialize(first = nil) self.first = first end def first=(first) @first = first end def first @first end end Instance Variables Private, per object storage
    93. 93. class Name def initialize(first = nil) self.first = first end def first=(first) @first = first end def first @first end end Instance Variables Private, per object storage
    94. 94. class Name def initialize(first = nil) self.first = first end dana = Name.new("Dana") james = Name.new def first=(first) james.first = "James" @first = first puts dana.first end puts james.first # >> Dana def first # >> James @first end end Instance Variables Private, per object storage
    95. 95. class Name def initialize(first = nil) self.first = first end dana = Name.new("Dana") james = Name.new def first=(first) james.first = "James" @first = first puts dana.first end puts james.first # >> Dana def first # >> James @first end end Instance Variables Private, per object storage
    96. 96. class Name def initialize(first = nil) self.first = first end dana = Name.new("Dana") james = Name.new def first=(first) james.first = "James" @first = first puts dana.first end puts james.first # >> Dana def first # >> James @first end end Instance Variables Private, per object storage
    97. 97. class Name def initialize(first = nil) self.first = first end dana = Name.new("Dana") james = Name.new def first=(first) james.first = "James" @first = first puts dana.first end puts james.first # >> Dana def first # >> James @first end end Instance Variables Private, per object storage
    98. 98. Single Inheritance
    99. 99. Single Inheritance class Parent def greet @greeting ||= "Hello!" end end class Child < Parent def initialize @greeting = "Yo!" end end puts Parent.new.greet puts Child.new.greet # >> Hello! # >> Yo!
    100. 100. Single Inheritance A Class can declare class Parent def greet one parent @greeting ||= "Hello!" end end class Child < Parent def initialize @greeting = "Yo!" end end puts Parent.new.greet puts Child.new.greet # >> Hello! # >> Yo!
    101. 101. Single Inheritance A Class can declare class Parent def greet one parent @greeting ||= "Hello!" end A child inherits all end class Child < Parent behavior from all def initialize @greeting = "Yo!" ancestors end end puts Parent.new.greet puts Child.new.greet # >> Hello! # >> Yo!
    102. 102. Single Inheritance A Class can declare class Parent def greet one parent @greeting ||= "Hello!" end A child inherits all end class Child < Parent behavior from all def initialize @greeting = "Yo!" ancestors end end Ruby’s Object is the puts Parent.new.greet puts Child.new.greet highest parent for all # >> Hello! Classes # >> Yo!
    103. 103. Questions and Dangerous Methods
    104. 104. Questions and Dangerous Methods >> 0.zero? => true >> 0.0.zero? => true >> 0.00001.zero? => false >> s = "string" => "string" >> s.upcase => "STRING" >> s => "string" >> s.upcase! => "STRING" >> s => "STRING"
    105. 105. Questions and Dangerous Methods Ruby has some >> => 0.zero? true method name >> => 0.0.zero? true conventions >> => 0.00001.zero? false >> s = "string" => "string" >> s.upcase => "STRING" >> s => "string" >> s.upcase! => "STRING" >> s => "STRING"
    106. 106. Questions and Dangerous Methods Ruby has some >> => 0.zero? true method name >> => 0.0.zero? true conventions >> => 0.00001.zero? false Question methods >> => s = "string" "string" (answering true or >> s.upcase => "STRING" false) end in ? >> s => "string" >> s.upcase! => "STRING" >> s => "STRING"
    107. 107. Questions and Dangerous Methods Ruby has some >> => 0.zero? true method name >> => 0.0.zero? true conventions >> => 0.00001.zero? false Question methods >> => s = "string" "string" (answering true or >> s.upcase => "STRING" false) end in ? >> s => "string" >> s.upcase! Dangerous methods => "STRING" >> s end in ! => "STRING"
    108. 108. “Mixins” A uniquely Ruby way to share methods
    109. 109. Modules
    110. 110. Modules module Netstring def to_netstring(*args) str = to_s(*args) "#{str.length}:#{str}," end end class String include Netstring end class Integer < Numeric include Netstring end p "James".to_netstring p 42.to_netstring(2) # >> "5:James," # >> "6:101010,"
    111. 111. Modules module Netstring def to_netstring(*args) Ruby doesn’t have str = to_s(*args) "#{str.length}:#{str}," multiple inheritance end end class String include Netstring end class Integer < Numeric include Netstring end p "James".to_netstring p 42.to_netstring(2) # >> "5:James," # >> "6:101010,"
    112. 112. Modules module Netstring def to_netstring(*args) Ruby doesn’t have str = to_s(*args) "#{str.length}:#{str}," multiple inheritance end end Instead, we can “mix” a class String include Netstring Module of methods end “in”to a Class class Integer < Numeric include Netstring end p "James".to_netstring p 42.to_netstring(2) # >> "5:James," # >> "6:101010,"
    113. 113. Modules module Netstring def to_netstring(*args) Ruby doesn’t have str = to_s(*args) "#{str.length}:#{str}," multiple inheritance end end Instead, we can “mix” a class String include Netstring Module of methods end “in”to a Class class Integer < Numeric include Netstring end We call these p "James".to_netstring Modules “mixins” p # 42.to_netstring(2) >> "5:James," # >> "6:101010,"
    114. 114. Modules module Netstring def to_netstring(*args) Ruby doesn’t have str = to_s(*args) "#{str.length}:#{str}," multiple inheritance end end Instead, we can “mix” a class String include Netstring Module of methods end “in”to a Class class Integer < Numeric include Netstring end We call these p "James".to_netstring Modules “mixins” p # 42.to_netstring(2) >> "5:James," # >> "6:101010,"
    115. 115. Blocks and Iterators Rubyists turn their noses up at loops
    116. 116. Blocks
    117. 117. Blocks def until_successful loop do break if yield == :success end end until_successful { puts "Called." :success if rand(3).zero? } # >> Called. # >> Called. # >> Called. # >> Called.
    118. 118. Blocks In Ruby, you can pass def until_successful a block (some code) to loop do break if yield == :success a called method end end until_successful { puts "Called." :success if rand(3).zero? } # >> Called. # >> Called. # >> Called. # >> Called.
    119. 119. Blocks In Ruby, you can pass def until_successful a block (some code) to loop do break if yield == :success a called method end end Block code is in until_successful { puts "Called." { … } or do … end :success if rand(3).zero? } # >> Called. # >> Called. # >> Called. # >> Called.
    120. 120. Blocks In Ruby, you can pass def until_successful a block (some code) to loop do break if yield == :success a called method end end Block code is in until_successful { puts "Called." { … } or do … end :success if rand(3).zero? } That method can run # >> Called. # >> Called. the passed code with # >> Called. # >> Called. yield
    121. 121. for (…; …; …) { }
    122. 122. for (…; …; …) { } Rubyists Don’t “Loop” We “iterate” instead
    123. 123. The each() Iterator
    124. 124. The each() Iterator name = %w[James Edward Gray II] name.each do |word| puts word.reverse end # >> semaJ # >> drawdE # >> yarG # >> II
    125. 125. The each() Iterator Let Ruby manage name = %w[James Edward Gray II] indexes for you name.each do |word| puts word.reverse end # >> semaJ # >> drawdE # >> yarG # >> II
    126. 126. The each() Iterator Let Ruby manage name = %w[James Edward Gray II] indexes for you name.each do |word| puts word.reverse end each() will call the # >> semaJ # >> drawdE block once with every # >> yarG # >> II item of the collection
    127. 127. The map() Iterator
    128. 128. The map() Iterator nums = *1..5 p nums p nums.map { |n| n ** 2 } # >> [1, 2, 3, 4, 5] # >> [1, 4, 9, 16, 25]
    129. 129. The map() Iterator map() is used to transform your collection nums = *1..5 p nums p nums.map { |n| n ** 2 } # >> [1, 2, 3, 4, 5] # >> [1, 4, 9, 16, 25]
    130. 130. The map() Iterator map() is used to transform your collection nums = *1..5 Each item of the p nums p nums.map { |n| n ** 2 } collection is passed # >> [1, 2, 3, 4, 5] into the block and the # >> [1, 4, 9, 16, 25] result of the block replaces that item in a new collection
    131. 131. The map() Iterator map() is used to transform your collection nums = *1..5 Each item of the p nums p nums.map { |n| n ** 2 } collection is passed # >> [1, 2, 3, 4, 5] into the block and the # >> [1, 4, 9, 16, 25] result of the block replaces that item in a new collection
    132. 132. The select() Iterator
    133. 133. The select() Iterator nums = *1..10 p nums p nums.select { |n| n % 2 == 0 } # >> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # >> [2, 4, 6, 8, 10]
    134. 134. The select() Iterator select() can be used to filter a collection nums = *1..10 p nums p nums.select { |n| n % 2 == 0 } # >> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # >> [2, 4, 6, 8, 10]
    135. 135. The select() Iterator select() can be used to filter a collection Each item is passed nums = *1..10 into the block and if the p nums p nums.select { |n| n % 2 == 0 } # >> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] block conditional # >> [2, 4, 6, 8, 10] evaluates to a true value the item is placed in the new collection
    136. 136. The select() Iterator select() can be used to filter a collection Each item is passed nums = *1..10 into the block and if the p nums p nums.select { |n| n % 2 == 0 } # >> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] block conditional # >> [2, 4, 6, 8, 10] evaluates to a true value the item is placed in the new collection
    137. 137. And Much, Much More! I have barely scratched the surface of Ruby
    138. 138. Ruby is a Rich Language
    139. 139. Ruby is a Rich Language Over 140 methods on String and over 70 on Array
    140. 140. Ruby is a Rich Language Over 140 methods on String and over 70 on Array Automatic “big math” conversions
    141. 141. Ruby is a Rich Language Over 140 methods on String and over 70 on Array Automatic “big math” conversions A very capable case statement (multi-branch conditional)
    142. 142. Ruby is a Rich Language Over 140 methods on String and over 70 on Array Automatic “big math” conversions A very capable case statement (multi-branch conditional) Custom per object behaviors
    143. 143. Ruby is a Rich Language Over 140 methods on String and over 70 on Array Automatic “big math” conversions A very capable case statement (multi-branch conditional) Custom per object behaviors Over 30 iterators
    144. 144. Ruby is a Rich Language Over 140 methods on String and over 70 on Array Automatic “big math” conversions A very capable case statement (multi-branch conditional) Custom per object behaviors Over 30 iterators Powerful reflection capabilities
    145. 145. Questions?
    146. 146. Learning Ruby from Ruby Lab Your book has instructions on how to use irb to learn more about Ruby from the language itself
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.

    ×