SlideShare ist ein Scribd-Unternehmen logo
1 von 148
Downloaden Sie, um offline zu lesen
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 in Rails,
so James will not come take my keyboard away!”
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
This is an excellent way to learn the language
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
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
Using irb
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
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
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
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
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
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
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 primary data structures: Array and Hash
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, …
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
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
Ruby
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)
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)
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)
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)
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)
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)
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)
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)
Working With Strings
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"
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"
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"
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"
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"
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"
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"
Working With Arrays
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]
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]
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]
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]
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]
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]
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]
Working With Hashes
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
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
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
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
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
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
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
Type Conversions
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"
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"
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"
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"
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"
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"
  …
Flow Control
Conditional logic
The if statement
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.
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.
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.
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.)
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.)
When Things go Wrong
When Things go Wrong


              >> 42 / 0
              ZeroDivisionError: divided by 0
               from (irb):1:in `/'
               from (irb):1
               from :0
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
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
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
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
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”
Exception Handling
Exception Handling


              >>   begin
              >>     n = 42 / 0
              >>   rescue ZeroDivisionError => error
              >>     n=0
              >>   end
              =>   0
              >>   n
              =>   0
Exception Handling

Put code that might
raise errors between   >>   begin
                       >>     n = 42 / 0
begin … end            >>
                       >>
                            rescue ZeroDivisionError => error
                              n=0
                       >>   end
                       =>   0
                       >>   n
                       =>   0
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
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" }
                Howdy
                Howdy
                Howdy
                => 3
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
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
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
 end
end




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
 end
end




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
 end
end




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
 end
end




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
 end
end




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
 end
end




Instance Variables
Private, per object storage
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
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
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
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
Single Inheritance
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!
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!
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!
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!
Questions and
Dangerous Methods
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"
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"
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"
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"
“Mixins”
A uniquely Ruby way to share methods
Modules
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,"
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,"
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,"
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,"
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,"
Blocks and Iterators
Rubyists turn their noses up at loops
Blocks
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.
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.
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.
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
Ruby
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|
                 puts word.reverse
                end
                # >> semaJ
                # >> drawdE
                # >> yarG
                # >> II
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
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
The map() Iterator
The map() Iterator


                nums = *1..5
                p nums
                p nums.map { |n| n ** 2 }
                # >> [1, 2, 3, 4, 5]
                # >> [1, 4, 9, 16, 25]
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]
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
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
The select() Iterator
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]
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]
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
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
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 case statement (multi-branch conditional)
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
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
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
Questions?
Learning Ruby
from Ruby Lab
Your book has instructions on how to use irb to
learn more about Ruby from the language itself

Weitere ähnliche Inhalte

Was ist angesagt?

The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212Mahmoud Samir Fayed
 
The Ring programming language version 1.4 book - Part 8 of 30
The Ring programming language version 1.4 book - Part 8 of 30The Ring programming language version 1.4 book - Part 8 of 30
The Ring programming language version 1.4 book - Part 8 of 30Mahmoud Samir Fayed
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기JangHyuk You
 
CS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBCS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBjorgeortiz85
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기Suyeol Jeon
 
Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperosfameron
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala LanguageAshal aka JOKER
 
λ | Lenses
λ | Lensesλ | Lenses
λ | LensesOpen-IT
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Suyeol Jeon
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applicationsSkills Matter
 
Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Stephen Chin
 
The Ring programming language version 1.5.2 book - Part 29 of 181
The Ring programming language version 1.5.2 book - Part 29 of 181The Ring programming language version 1.5.2 book - Part 29 of 181
The Ring programming language version 1.5.2 book - Part 29 of 181Mahmoud Samir Fayed
 
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingGareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingYury Chemerkin
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うbpstudy
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007Damien Seguy
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)Zach Bray
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwoEishay Smith
 

Was ist angesagt? (20)

The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212The Ring programming language version 1.10 book - Part 47 of 212
The Ring programming language version 1.10 book - Part 47 of 212
 
The Ring programming language version 1.4 book - Part 8 of 30
The Ring programming language version 1.4 book - Part 8 of 30The Ring programming language version 1.4 book - Part 8 of 30
The Ring programming language version 1.4 book - Part 8 of 30
 
Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기Programming Lisp Clojure - 2장 : 클로저 둘러보기
Programming Lisp Clojure - 2장 : 클로저 둘러보기
 
CS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDBCS442 - Rogue: A Scala DSL for MongoDB
CS442 - Rogue: A Scala DSL for MongoDB
 
RxSwift 시작하기
RxSwift 시작하기RxSwift 시작하기
RxSwift 시작하기
 
Functional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipperFunctional pe(a)rls: Huey's zipper
Functional pe(a)rls: Huey's zipper
 
여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language여자개발자모임터 6주년 개발 세미나 - Scala Language
여자개발자모임터 6주년 개발 세미나 - Scala Language
 
λ | Lenses
λ | Lensesλ | Lenses
λ | Lenses
 
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
Swift - 혼자 공부하면 분명히 안할테니까 같이 공부하기
 
Patterns for slick database applications
Patterns for slick database applicationsPatterns for slick database applications
Patterns for slick database applications
 
Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)Mary Had a Little λ (QCon)
Mary Had a Little λ (QCon)
 
The Ring programming language version 1.5.2 book - Part 29 of 181
The Ring programming language version 1.5.2 book - Part 29 of 181The Ring programming language version 1.5.2 book - Part 29 of 181
The Ring programming language version 1.5.2 book - Part 29 of 181
 
Beyond Scala Lens
Beyond Scala LensBeyond Scala Lens
Beyond Scala Lens
 
7li7w devcon5
7li7w devcon57li7w devcon5
7li7w devcon5
 
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzingGareth hayes. non alphanumeric javascript-php and shared fuzzing
Gareth hayes. non alphanumeric javascript-php and shared fuzzing
 
ハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使うハイブリッド言語Scalaを使う
ハイブリッド言語Scalaを使う
 
PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007PHP and MySQL Tips and tricks, DC 2007
PHP and MySQL Tips and tricks, DC 2007
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 
FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)FunScript 2013 (with speakers notes)
FunScript 2013 (with speakers notes)
 
Using Scala Slick at FortyTwo
Using Scala Slick at FortyTwoUsing Scala Slick at FortyTwo
Using Scala Slick at FortyTwo
 

Andere mochten auch

comScore Inc. - 2013 Mobile Future in Focus
comScore Inc. - 2013 Mobile Future in FocuscomScore Inc. - 2013 Mobile Future in Focus
comScore Inc. - 2013 Mobile Future in FocusSunny Kr
 
Harper College Scholars Prez
Harper College Scholars   PrezHarper College Scholars   Prez
Harper College Scholars PrezMaria Thompson
 
Covenant eyes app for android
Covenant eyes app for android Covenant eyes app for android
Covenant eyes app for android rwpike
 
The Battle of Trafalgar
The Battle of TrafalgarThe Battle of Trafalgar
The Battle of TrafalgarYasmeen Od
 

Andere mochten auch (6)

comScore Inc. - 2013 Mobile Future in Focus
comScore Inc. - 2013 Mobile Future in FocuscomScore Inc. - 2013 Mobile Future in Focus
comScore Inc. - 2013 Mobile Future in Focus
 
Amis Presentation
Amis  PresentationAmis  Presentation
Amis Presentation
 
Harper College Scholars Prez
Harper College Scholars   PrezHarper College Scholars   Prez
Harper College Scholars Prez
 
Covenant eyes app for android
Covenant eyes app for android Covenant eyes app for android
Covenant eyes app for android
 
The Battle of Trafalgar
The Battle of TrafalgarThe Battle of Trafalgar
The Battle of Trafalgar
 
Microsoft Access
Microsoft AccessMicrosoft Access
Microsoft Access
 

Ähnlich wie Ruby

And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...Codemotion
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Wen-Tien Chang
 
Elm introduction
Elm   introductionElm   introduction
Elm introductionMix & Go
 
On Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian PerspectiveOn Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian Perspectivelooselytyped
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)Kerry Buckley
 

Ähnlich wie Ruby (10)

And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...And now you have two problems. Ruby regular expressions for fun and profit by...
And now you have two problems. Ruby regular expressions for fun and profit by...
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Introducing Elixir
Introducing ElixirIntroducing Elixir
Introducing Elixir
 
Elm introduction
Elm   introductionElm   introduction
Elm introduction
 
On Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian PerspectiveOn Functional Programming - A Clojurian Perspective
On Functional Programming - A Clojurian Perspective
 
Ruby 1.9
Ruby 1.9Ruby 1.9
Ruby 1.9
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)
 
The Magic Of Elixir
The Magic Of ElixirThe Magic Of Elixir
The Magic Of Elixir
 

Mehr von James Gray

A Dickens of A Keynote
A Dickens of A KeynoteA Dickens of A Keynote
A Dickens of A KeynoteJames Gray
 
Regular expressions
Regular expressionsRegular expressions
Regular expressionsJames Gray
 
Counting on God
Counting on GodCounting on God
Counting on GodJames Gray
 
In the Back of Your Mind
In the Back of Your MindIn the Back of Your Mind
In the Back of Your MindJames Gray
 
Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)James Gray
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHubJames Gray
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in RailsJames Gray
 
Rails Routing And Rendering
Rails Routing And RenderingRails Routing And Rendering
Rails Routing And RenderingJames Gray
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with RailsJames Gray
 
Associations in Rails
Associations in RailsAssociations in Rails
Associations in RailsJames Gray
 
DRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersDRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersJames Gray
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails InterfaceJames Gray
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model BasicsJames Gray
 
Wed Development on Rails
Wed Development on RailsWed Development on Rails
Wed Development on RailsJames Gray
 

Mehr von James Gray (18)

A Dickens of A Keynote
A Dickens of A KeynoteA Dickens of A Keynote
A Dickens of A Keynote
 
I Doubt That!
I Doubt That!I Doubt That!
I Doubt That!
 
Regular expressions
Regular expressionsRegular expressions
Regular expressions
 
Counting on God
Counting on GodCounting on God
Counting on God
 
In the Back of Your Mind
In the Back of Your MindIn the Back of Your Mind
In the Back of Your Mind
 
Unblocked
UnblockedUnblocked
Unblocked
 
Module Magic
Module MagicModule Magic
Module Magic
 
API Design
API DesignAPI Design
API Design
 
Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHub
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in Rails
 
Rails Routing And Rendering
Rails Routing And RenderingRails Routing And Rendering
Rails Routing And Rendering
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
 
Associations in Rails
Associations in RailsAssociations in Rails
Associations in Rails
 
DRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersDRYing Up Rails Views and Controllers
DRYing Up Rails Views and Controllers
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails Interface
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model Basics
 
Wed Development on Rails
Wed Development on RailsWed Development on Rails
Wed Development on Rails
 

Kürzlich hochgeladen

Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioChristian Posta
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?SANGHEE SHIN
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncObject Automation
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024SkyPlanner
 
Babel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxBabel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxYounusS2
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.francesco barbera
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfDianaGray10
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URLRuncy Oommen
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfAnna Loughnan Colquhoun
 

Kürzlich hochgeladen (20)

Comparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and IstioComparing Sidecar-less Service Mesh from Cilium and Istio
Comparing Sidecar-less Service Mesh from Cilium and Istio
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?
 
GenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation IncGenAI and AI GCC State of AI_Object Automation Inc
GenAI and AI GCC State of AI_Object Automation Inc
 
Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024Salesforce Miami User Group Event - 1st Quarter 2024
Salesforce Miami User Group Event - 1st Quarter 2024
 
Babel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptxBabel Compiler - Transforming JavaScript for All Browsers.pptx
Babel Compiler - Transforming JavaScript for All Browsers.pptx
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.Digital magic. A small project for controlling smart light bulbs.
Digital magic. A small project for controlling smart light bulbs.
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdfUiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
UiPath Solutions Management Preview - Northern CA Chapter - March 22.pdf
 
Designing A Time bound resource download URL
Designing A Time bound resource download URLDesigning A Time bound resource download URL
Designing A Time bound resource download URL
 
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdf
 

Ruby

  • 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. irb The secret weapon of the Rubyists
  • 6. The REPL Ruby comes with a Read-Eval-Print-Loop tool called irb
  • 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. 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. 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. 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
  • 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. 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. 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. 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. 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. 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. Data Types The building blocks of Ruby
  • 19. Data Types and Structures
  • 20. Data Types and Structures Ruby has data types common to most programming languages: String, Integer, Float, …
  • 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. 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. 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. 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
  • 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. 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. 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. 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. 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. 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. 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. 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)
  • 35. 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"
  • 36. 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"
  • 37. 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"
  • 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" >> date = "March 2010" => "March 2010" >> date[0..4] => "March" >> date[-2..-1] => "10" >> date[/d+/] => "2010"
  • 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] => "March" >> date[-2..-1] => "10" >> date[/d+/] => "2010"
  • 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. 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"
  • 43. 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]
  • 44. 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]
  • 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 => [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. 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]
  • 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] >> a & [0, 2, 4, 6] => [0, 2] >> a | [42] => [0, 1, 2, 3, 42]
  • 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. 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]
  • 51. 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
  • 52. 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
  • 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 => {: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. 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
  • 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] >> h.include? :c => true >> h.include? :d => false
  • 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. 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
  • 59. 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"
  • 60. 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"
  • 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" >> 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"
  • 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" >> animals.split(",") => ["chickens", "cows", "Rubyists"] >> animals.split(",", 2) => ["chickens", "cows,Rubyists"] >> animals.split(",").join(" | ") => "chickens | cows | Rubyists"
  • 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. 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" …
  • 67. 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.
  • 68. 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.
  • 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." else puts "A boring number." end # >> 2: A little low.
  • 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. 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.)
  • 72. When Things go Wrong
  • 73. When Things go Wrong >> 42 / 0 ZeroDivisionError: divided by 0 from (irb):1:in `/' from (irb):1 from :0
  • 74. 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
  • 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. 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. 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
  • 78. 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”
  • 80. Exception Handling >> begin >> n = 42 / 0 >> rescue ZeroDivisionError => error >> n=0 >> end => 0 >> n => 0
  • 81. Exception Handling Put code that might raise errors between >> begin >> n = 42 / 0 begin … end >> >> rescue ZeroDivisionError => error n=0 >> end => 0 >> n => 0
  • 82. 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
  • 83. Objects and Methods In Ruby, very nearly everything is an object
  • 85. Everything is an Object >> -42.abs => 42 >> 3.times { puts "Howdy" } Howdy Howdy Howdy => 3
  • 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 Howdy => 3
  • 87. 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
  • 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. 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. 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. 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. 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. 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
  • 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. 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. 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. 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
  • 100. 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!
  • 101. 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!
  • 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 puts Parent.new.greet puts Child.new.greet # >> Hello! # >> Yo!
  • 103. 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!
  • 105. 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"
  • 106. 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"
  • 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! => "STRING" >> s => "STRING"
  • 108. 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"
  • 109. “Mixins” A uniquely Ruby way to share methods
  • 111. 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,"
  • 112. 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,"
  • 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 p "James".to_netstring p 42.to_netstring(2) # >> "5:James," # >> "6:101010,"
  • 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. 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,"
  • 116. Blocks and Iterators Rubyists turn their noses up at loops
  • 117. Blocks
  • 118. 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.
  • 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 until_successful { puts "Called." :success if rand(3).zero? } # >> Called. # >> Called. # >> Called. # >> Called.
  • 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? } # >> Called. # >> Called. # >> Called. # >> Called.
  • 121. 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
  • 123. for (…; …; …) { }
  • 124. for (…; …; …) { } Rubyists Don’t “Loop” We “iterate” instead
  • 126. The each() Iterator name = %w[James Edward Gray II] name.each do |word| puts word.reverse end # >> semaJ # >> drawdE # >> yarG # >> II
  • 127. 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
  • 128. 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
  • 130. The map() Iterator nums = *1..5 p nums p nums.map { |n| n ** 2 } # >> [1, 2, 3, 4, 5] # >> [1, 4, 9, 16, 25]
  • 131. 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]
  • 132. 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
  • 133. 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
  • 135. 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]
  • 136. 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]
  • 137. 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
  • 138. 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
  • 139. And Much, Much More! I have barely scratched the surface of Ruby
  • 140. Ruby is a Rich Language
  • 141. Ruby is a Rich Language Over 140 methods on String and over 70 on Array
  • 142. Ruby is a Rich Language Over 140 methods on String and over 70 on Array Automatic “big math” conversions
  • 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)
  • 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
  • 145. 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
  • 146. 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
  • 148. Learning Ruby from Ruby Lab Your book has instructions on how to use irb to learn more about Ruby from the language itself

Hinweis der Redaktion