SlideShare une entreprise Scribd logo
1  sur  12
COLLECTIONS & ITERATORS
      WITH HASHES AND ARRAYS




            Sarah Allen
ITERATORS: CONDITIONAL
          LOOPING
• “while” allows us to loop through code while a set condition is
  true

              x = 1
              while x < 10
               puts x.to_s + “ iteration”
               x += 1
              end
TIMES
5.times { puts “hello” }
5.times { |num| puts “hi”+num.to_s }

99.times do |beer_num|
    puts "#{beer_num} bottles of beer”
end

99.times do
  puts "some bottles of beer”
end
CREATING A NEW ARRAY
    x = [1, 2, 3, 4]
    => [1, 2, 3, 4]

    x = %w(1 2 3 4)
    => [“1”, “2”, “3”, “4”]

    chef = Array.new(3,
      “bork”)
    => [“bork”, “bork”, bork”]
ACCESSING ARRAY VALUES
a = [ "a", "b", "c", "d", "e" ]
a[0] #=> "a”

a[2] #=> "c”

a[6] #=> nil

a[1, 2] #=> ["b", "c”]

a[1..3] #=> ["b", "c", "d”]

a[1…3] #=> ["b", "c"]
RANGES
Inclusive
1..4# => runs 1 thru 4
(1..4).to_a# => [1,2,3,4]


Exclusive
1...4# => runs 1 thru 3
(1...4).to_a # => [1,2,3]
OPERATIONS ON ARRAYS
[ 1, 2, 3 ] * 3
=> [1, 2, 3, 1, 2, 3, 1, 2, 3]


[ 1, 2, 3 ].join(“,”)
⇒   "1,2,3”


[ 1, 2, 3 ] + [ 4, 5 ]
=> [1, 2, 3, 4, 5]


[ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ]
=> [3, 3, 5]


[ 1, 2 ] << "c" << "d" << [ 3, 4 ]
=> [1, 2, "c", "d", [3, 4]]
CREATING A HASH
h = { "a" => 100, "b" => 200 }

h["a"]




h = { 1 => "a", "b" => “hello” }

h[1]
OPERATIONS ON HASHES:
           MERGE
h1 = { "a" => 100, "b" => 200 }
=> {"a"=>100, "b"=>200}
h2 = { "b" => 254, "c" => 300 }
=>{"b"=>254, "c"=>300}

h3 = h1.merge(h2)
=> {"a"=>100, "b"=>254, "c"=>300}
h1
=> {"a"=>100, "b"=>200}

h1.merge!(h2)
=> {"a"=>100, "b"=>254, "c"=>300}
OPERATIONS ON HASHES
h = { "a" => 100, "b" => 200 }
h.delete("a”)


h = { "a" => 100, "b" => 200, "c" => 300, "d"
  => 400 }
letters = h.keys


h = { "a" => 100, "b" => 200, "c" => 300 }
numbers = h.values
EACH
>> superheroes = ["catwoman", "batman", "wonderwoman"]
>> superheroes.each { | s | puts "#{ s } save me!" }
catwoman save me!
batman save me!
wonderwoman save me!

>>   dogs = ["fido", "fifi", "rex", "fluffy"]
>>   dogs_i_want = []
>>   dogs.each do |dog|
>?      dogs_i_want.push(dog) if dog != "fluffy"
>?   end

>>   dogs
=>   ["fido", "fifi", "rex", "fluffy"]
>>   dogs_i_want
=>   ["fido", "fifi", "rex"]
MAP
superheroes = ["catwoman", "batman", "wonderwoman"]



>> superheroes.map { |s| s.upcase }

=> ["CATWOMAN", "BATMAN", "WONDERWOMAN"]



Shorter (available in Rails or Ruby 1.8.7+):

>> superheroes.map(&:upcase)

Contenu connexe

Tendances

September 2018 calendar
September 2018 calendarSeptember 2018 calendar
September 2018 calendarFloodwoodvern
 
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn Systemit-people
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Pythonpugpe
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cythonAnderson Dantas
 
Preliminary results of EJC survey on training needs for data journalism
Preliminary results of EJC survey on training needs for data journalismPreliminary results of EJC survey on training needs for data journalism
Preliminary results of EJC survey on training needs for data journalismLiliana Bounegru
 
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPlotly
 
Extending Operators in Perl with Operator::Util
Extending Operators in Perl with Operator::UtilExtending Operators in Perl with Operator::Util
Extending Operators in Perl with Operator::UtilNova Patch
 
{tidygraph}と{ggraph}によるモダンなネットワーク分析
{tidygraph}と{ggraph}によるモダンなネットワーク分析{tidygraph}と{ggraph}によるモダンなネットワーク分析
{tidygraph}と{ggraph}によるモダンなネットワーク分析Takashi Kitano
 
Dipôles linéaires, régime transitoire
Dipôles linéaires, régime transitoireDipôles linéaires, régime transitoire
Dipôles linéaires, régime transitoireAchraf Ourti
 
Python data structures
Python data structuresPython data structures
Python data structuresHarry Potter
 

Tendances (17)

September 2018 calendar
September 2018 calendarSeptember 2018 calendar
September 2018 calendar
 
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
«PyWat. А хорошо ли вы знаете Python?» Александр Швец, Marilyn System
 
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه سوم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
The Magic Of Elixir
The Magic Of ElixirThe Magic Of Elixir
The Magic Of Elixir
 
FVS Training Bolzano 8/9
FVS Training Bolzano 8/9FVS Training Bolzano 8/9
FVS Training Bolzano 8/9
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
Groupes
GroupesGroupes
Groupes
 
PHP 101
PHP 101 PHP 101
PHP 101
 
Clustering com numpy e cython
Clustering com numpy e cythonClustering com numpy e cython
Clustering com numpy e cython
 
Preliminary results of EJC survey on training needs for data journalism
Preliminary results of EJC survey on training needs for data journalismPreliminary results of EJC survey on training needs for data journalism
Preliminary results of EJC survey on training needs for data journalism
 
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of WranglingPLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
PLOTCON NYC: Behind Every Great Plot There's a Great Deal of Wrangling
 
Extending Operators in Perl with Operator::Util
Extending Operators in Perl with Operator::UtilExtending Operators in Perl with Operator::Util
Extending Operators in Perl with Operator::Util
 
{tidygraph}と{ggraph}によるモダンなネットワーク分析
{tidygraph}と{ggraph}によるモダンなネットワーク分析{tidygraph}と{ggraph}によるモダンなネットワーク分析
{tidygraph}と{ggraph}によるモダンなネットワーク分析
 
Pets and Pandas.
Pets and Pandas.Pets and Pandas.
Pets and Pandas.
 
kan r_ifels
kan r_ifelskan r_ifels
kan r_ifels
 
Dipôles linéaires, régime transitoire
Dipôles linéaires, régime transitoireDipôles linéaires, régime transitoire
Dipôles linéaires, régime transitoire
 
Python data structures
Python data structuresPython data structures
Python data structures
 

En vedette

Som what is seo and how to levirage it
Som   what is seo and how to levirage itSom   what is seo and how to levirage it
Som what is seo and how to levirage itAidawsCkarl
 
19th cen art 1213
19th cen art 121319th cen art 1213
19th cen art 1213mloret
 
Cambodia Group, AIT SRI
Cambodia Group, AIT SRICambodia Group, AIT SRI
Cambodia Group, AIT SRISri Lmb
 
open source intro
open source introopen source intro
open source introKanchilug
 
Books of the new testament
Books of the new testamentBooks of the new testament
Books of the new testamentkirathered
 
Mom power point breakthrough branding may 2013
Mom power point   breakthrough branding  may 2013Mom power point   breakthrough branding  may 2013
Mom power point breakthrough branding may 2013Carolyn Parrs
 

En vedette (7)

Tanácsok
TanácsokTanácsok
Tanácsok
 
Som what is seo and how to levirage it
Som   what is seo and how to levirage itSom   what is seo and how to levirage it
Som what is seo and how to levirage it
 
19th cen art 1213
19th cen art 121319th cen art 1213
19th cen art 1213
 
Cambodia Group, AIT SRI
Cambodia Group, AIT SRICambodia Group, AIT SRI
Cambodia Group, AIT SRI
 
open source intro
open source introopen source intro
open source intro
 
Books of the new testament
Books of the new testamentBooks of the new testament
Books of the new testament
 
Mom power point breakthrough branding may 2013
Mom power point   breakthrough branding  may 2013Mom power point   breakthrough branding  may 2013
Mom power point breakthrough branding may 2013
 

Similaire à Iterators, Hashes, and Arrays

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
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Useful javascript
Useful javascriptUseful javascript
Useful javascriptLei Kang
 
Parse Everything With Elixir
Parse Everything With ElixirParse Everything With Elixir
Parse Everything With ElixirGabriele Lana
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick touraztack
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonUC San Diego
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About RubyIan Bishop
 
Python WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorPython WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorAmy Hanlon
 
A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009Jordan Baker
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is AwesomeAstrails
 
Investigating Python Wats
Investigating Python WatsInvestigating Python Wats
Investigating Python WatsAmy Hanlon
 
RedDot Ruby Conf 2014 - Dark side of ruby
RedDot Ruby Conf 2014 - Dark side of ruby RedDot Ruby Conf 2014 - Dark side of ruby
RedDot Ruby Conf 2014 - Dark side of ruby Gautam Rege
 
Ruby初級者向けレッスン 48回 ─── Array と Hash
Ruby初級者向けレッスン 48回 ─── Array と HashRuby初級者向けレッスン 48回 ─── Array と Hash
Ruby初級者向けレッスン 48回 ─── Array と Hashhigaki
 

Similaire à Iterators, Hashes, and Arrays (20)

Swift Study #2
Swift Study #2Swift Study #2
Swift Study #2
 
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
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Elixir
ElixirElixir
Elixir
 
Useful javascript
Useful javascriptUseful javascript
Useful javascript
 
Parse Everything With Elixir
Parse Everything With ElixirParse Everything With Elixir
Parse Everything With Elixir
 
Ruby Language - A quick tour
Ruby Language - A quick tourRuby Language - A quick tour
Ruby Language - A quick tour
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Let’s Talk About Ruby
Let’s Talk About RubyLet’s Talk About Ruby
Let’s Talk About Ruby
 
Python WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd BehaviorPython WATs: Uncovering Odd Behavior
Python WATs: Uncovering Odd Behavior
 
A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009A Taste of Python - Devdays Toronto 2009
A Taste of Python - Devdays Toronto 2009
 
Ruby is Awesome
Ruby is AwesomeRuby is Awesome
Ruby is Awesome
 
Investigating Python Wats
Investigating Python WatsInvestigating Python Wats
Investigating Python Wats
 
RedDot Ruby Conf 2014 - Dark side of ruby
RedDot Ruby Conf 2014 - Dark side of ruby RedDot Ruby Conf 2014 - Dark side of ruby
RedDot Ruby Conf 2014 - Dark side of ruby
 
Basics
BasicsBasics
Basics
 
P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
 
Intoduction to php arrays
Intoduction to php arraysIntoduction to php arrays
Intoduction to php arrays
 
P2 2017 python_strings
P2 2017 python_stringsP2 2017 python_strings
P2 2017 python_strings
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Ruby初級者向けレッスン 48回 ─── Array と Hash
Ruby初級者向けレッスン 48回 ─── Array と HashRuby初級者向けレッスン 48回 ─── Array と Hash
Ruby初級者向けレッスン 48回 ─── Array と Hash
 

Plus de Blazing Cloud

Rails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyRails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyBlazing Cloud
 
Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3Blazing Cloud
 
Rails Class Intro - 1
Rails Class Intro - 1 Rails Class Intro - 1
Rails Class Intro - 1 Blazing Cloud
 
Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2Blazing Cloud
 
RSpec Quick Reference
RSpec Quick ReferenceRSpec Quick Reference
RSpec Quick ReferenceBlazing Cloud
 
2day Ruby Class Intro
2day Ruby Class Intro2day Ruby Class Intro
2day Ruby Class IntroBlazing Cloud
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive GraphicsBlazing Cloud
 
Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3Blazing Cloud
 
Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)Blazing Cloud
 
What you don't know (yet)
What you don't know (yet)What you don't know (yet)
What you don't know (yet)Blazing Cloud
 
Introduction to Rails
Introduction to RailsIntroduction to Rails
Introduction to RailsBlazing Cloud
 
Ruby on Rails Class intro
Ruby on Rails Class introRuby on Rails Class intro
Ruby on Rails Class introBlazing Cloud
 
Ruby on rails toolbox
Ruby on rails toolboxRuby on rails toolbox
Ruby on rails toolboxBlazing Cloud
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven DevelopmentBlazing Cloud
 

Plus de Blazing Cloud (20)

Rails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_manyRails ORM De-mystifying Active Record has_many
Rails ORM De-mystifying Active Record has_many
 
Active Record Introduction - 3
Active Record Introduction - 3Active Record Introduction - 3
Active Record Introduction - 3
 
Rails Class Intro - 1
Rails Class Intro - 1 Rails Class Intro - 1
Rails Class Intro - 1
 
Your first rails app - 2
 Your first rails app - 2 Your first rails app - 2
Your first rails app - 2
 
RSpec Quick Reference
RSpec Quick ReferenceRSpec Quick Reference
RSpec Quick Reference
 
Extending rails
Extending railsExtending rails
Extending rails
 
2day Ruby Class Intro
2day Ruby Class Intro2day Ruby Class Intro
2day Ruby Class Intro
 
Mobile Lean UX
Mobile Lean UXMobile Lean UX
Mobile Lean UX
 
Interactive Graphics
Interactive GraphicsInteractive Graphics
Interactive Graphics
 
Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3Interactive Graphics w/ Javascript, HTML5 and CSS3
Interactive Graphics w/ Javascript, HTML5 and CSS3
 
Form helpers
Form helpersForm helpers
Form helpers
 
Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)Intro to Ruby (and RSpec)
Intro to Ruby (and RSpec)
 
What you don't know (yet)
What you don't know (yet)What you don't know (yet)
What you don't know (yet)
 
Introduction to Rails
Introduction to RailsIntroduction to Rails
Introduction to Rails
 
ActiveRecord
ActiveRecordActiveRecord
ActiveRecord
 
Ruby on Rails Class intro
Ruby on Rails Class introRuby on Rails Class intro
Ruby on Rails Class intro
 
Ruby on rails toolbox
Ruby on rails toolboxRuby on rails toolbox
Ruby on rails toolbox
 
Routes Controllers
Routes ControllersRoutes Controllers
Routes Controllers
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Active Record
Active RecordActive Record
Active Record
 

Iterators, Hashes, and Arrays

  • 1. COLLECTIONS & ITERATORS WITH HASHES AND ARRAYS Sarah Allen
  • 2. ITERATORS: CONDITIONAL LOOPING • “while” allows us to loop through code while a set condition is true x = 1 while x < 10 puts x.to_s + “ iteration” x += 1 end
  • 3. TIMES 5.times { puts “hello” } 5.times { |num| puts “hi”+num.to_s } 99.times do |beer_num| puts "#{beer_num} bottles of beer” end 99.times do puts "some bottles of beer” end
  • 4. CREATING A NEW ARRAY x = [1, 2, 3, 4] => [1, 2, 3, 4] x = %w(1 2 3 4) => [“1”, “2”, “3”, “4”] chef = Array.new(3, “bork”) => [“bork”, “bork”, bork”]
  • 5. ACCESSING ARRAY VALUES a = [ "a", "b", "c", "d", "e" ] a[0] #=> "a” a[2] #=> "c” a[6] #=> nil a[1, 2] #=> ["b", "c”] a[1..3] #=> ["b", "c", "d”] a[1…3] #=> ["b", "c"]
  • 6. RANGES Inclusive 1..4# => runs 1 thru 4 (1..4).to_a# => [1,2,3,4] Exclusive 1...4# => runs 1 thru 3 (1...4).to_a # => [1,2,3]
  • 7. OPERATIONS ON ARRAYS [ 1, 2, 3 ] * 3 => [1, 2, 3, 1, 2, 3, 1, 2, 3] [ 1, 2, 3 ].join(“,”) ⇒ "1,2,3” [ 1, 2, 3 ] + [ 4, 5 ] => [1, 2, 3, 4, 5] [ 1, 1, 2, 2, 3, 3, 4, 5 ] - [ 1, 2, 4 ] => [3, 3, 5] [ 1, 2 ] << "c" << "d" << [ 3, 4 ] => [1, 2, "c", "d", [3, 4]]
  • 8. CREATING A HASH h = { "a" => 100, "b" => 200 } h["a"] h = { 1 => "a", "b" => “hello” } h[1]
  • 9. OPERATIONS ON HASHES: MERGE h1 = { "a" => 100, "b" => 200 } => {"a"=>100, "b"=>200} h2 = { "b" => 254, "c" => 300 } =>{"b"=>254, "c"=>300} h3 = h1.merge(h2) => {"a"=>100, "b"=>254, "c"=>300} h1 => {"a"=>100, "b"=>200} h1.merge!(h2) => {"a"=>100, "b"=>254, "c"=>300}
  • 10. OPERATIONS ON HASHES h = { "a" => 100, "b" => 200 } h.delete("a”) h = { "a" => 100, "b" => 200, "c" => 300, "d" => 400 } letters = h.keys h = { "a" => 100, "b" => 200, "c" => 300 } numbers = h.values
  • 11. EACH >> superheroes = ["catwoman", "batman", "wonderwoman"] >> superheroes.each { | s | puts "#{ s } save me!" } catwoman save me! batman save me! wonderwoman save me! >> dogs = ["fido", "fifi", "rex", "fluffy"] >> dogs_i_want = [] >> dogs.each do |dog| >? dogs_i_want.push(dog) if dog != "fluffy" >? end >> dogs => ["fido", "fifi", "rex", "fluffy"] >> dogs_i_want => ["fido", "fifi", "rex"]
  • 12. MAP superheroes = ["catwoman", "batman", "wonderwoman"] >> superheroes.map { |s| s.upcase } => ["CATWOMAN", "BATMAN", "WONDERWOMAN"] Shorter (available in Rails or Ruby 1.8.7+): >> superheroes.map(&:upcase)

Notes de l'éditeur

  1. \n
  2. \n
  3. 5 is an object that is an instance of the integer class\ntimes is a method of the 5 object\ntimes is a method on an object that is an instance of integer\n
  4. A lot of the time you will be using an array when you iterate over something\nAn array is just a list of items. \nEvery spot in the list acts like a variable and you can make each spot point to a different object\n\nW means words\n\nArray is a class, needs to start with capital letter\n
  5. IRB\nif you go off the array it will be nil\n
  6. \n
  7. join is cool because it makes a string for you\n\nshovel operator\n\nmultidimensional array\n
  8. Does anyone know what a hash is? \nassociative array \ncollection of key-value pairs\nkeys can be numbers or strings \n\nDifference from an Array\n
  9. merge takes the value from the second hash\nmerge! changes h1\n
  10. you would think that delete should need a bang to change the hash, but delete doesn&amp;#x2019;t exist with a bang\ndelete returns the value\n
  11. \n
  12. \n