• Shuffle
    Toggle On
    Toggle Off
  • Alphabetize
    Toggle On
    Toggle Off
  • Front First
    Toggle On
    Toggle Off
  • Both Sides
    Toggle On
    Toggle Off
  • Read
    Toggle On
    Toggle Off
Reading...
Front

Card Range To Study

through

image

Play button

image

Play button

image

Progress

1/32

Click to flip

Use LEFT and RIGHT arrow keys to navigate between flashcards;

Use UP and DOWN arrow keys to flip the card;

H to show hint;

A reads text to speech;

32 Cards in this Set

  • Front
  • Back

Enumberable methods are designed to _____, _____ or _____ collections.

Enumberable methods are designed to traverse, search or sort collections.



Traverse = to travel through


Search = traverse and locate a specific result (including boolean values)


Sort = arrange elements in a certain order

True or false? Enumerable methods can be called on both arrays and hashes?

True (in general). Enumerables work with collections, whether they are hashes or arrays.



Note that several Enumerables will return new arrays even if you are working with hashes (or rather, arrays do not automatically return arrays, hashes do not automatically return new hashes, etc.).

Explain the difference between these two methods:



.each



.map (also called .collect)

Both .each and .map/collect apply the values within a given block once for each element in the array or hash. The difference is that .map/collect returns a new array.



ex. a = [ "a", "b", "c", "d" ]


a.each {|x| print x, "*" } #=> a*b*c*d*


a.collect { |x| x + "!" } #=> ["a!", "b!", "c!", "d!"]

What is the end result of the following code?



a = %w(taco burrito quesadilla tostada)


a.each { |food| puts food}

Result:



taco
burrito
quesadilla
tostada

What is the end result of the following code?



a = %w(taco burrito fajitas)


hangry = a.map { |food| food.upcase }

Result:



We now have a new array called hangry in addition to the original a array:


a = ["taco", "burrito", "fajitas"]


hangry = ["TACO", "BURRITO", "FAJITAS"]



Both examples below use the sort method. Explain the difference between them:


example 1:


b= %w(blue red green)


b.sort



example 2:


b= %w(blue red green).sort

The difference:


In example 1 you created a new array called b and then sorted it. The end result is ["blue", "green", "red"], but b still equals ["blue", "red", "green"]. (Sort does not return a new array.)


In example 2, you combined the sort method with the creation of the initial array, so b immediately equals ["blue", "green", "red"].

Using the sort_by method, write a simple code example that creates an array called yum containing three fruits (pear, apple and fig) arranged by the numbers of letters in each word.



For bonus points, make the sorted array something you can use again.

Answer: ["fig", "pear", "apple"]


yum = ["pear", "apple", "fig"]


yum.sort_by { |word| word.length}


Bonus:


add a bang to the sort_by above (sort_by!), changing it permanently


OR sortedyum = yum.sort_by { |word| word.length}


OR yum = %w{pear apple fig}.sort_by { |word| word.length}

Use reduce (also called .inject) to take the following range of numbers and add them up into one number:


(1..7)

(1..7).reduce(:+)


or


(1..7).inject(:+)



Note that the longer way to do this with a block would be:


(1..7).reduce { |sum, n| sum + n }


Using .reduce or .inject, multiply the following range of numbers together using both short and longer (with a block) code examples:


(4..6)



The result should be 120 both times.

Short way:


(4..6).reduce(:*)



A longer way:


(4..6).inject { |product, n| product * n }


There are other even longer ways but... come on.

Can you figure out what the following code returns and why?



a = %w{ cat sheep bear }.reduce do|memo, word|


memo.length > word.length ? memo : word



Hint: google the ternary operator

Answer: "sheep"


This code returns the longest word in the array.


a = %w{ cat sheep bear }.reduce do|memo, word|


memo.length > word.length ? memo : word



For more on how this works, look closely at the Ruby Docs Enumerable explanation of reduce/inject in addition to learning more about ternary.

The .select (or .find_all) method searches a collection and returns an array containing all elements for which the given block returns true.



Using .select/.find_all, return all the even numbers from the following array: [1,2,3,4,5,6,7,8]

Return all even numbers from [1,2,3,4,5,6,7,8]



a.select { |num| num % 2 == 0 }


This returns all numbers that can be exactly divided by 2, aka even ones.


OR


a.select { |num| num.even? }

Using .select/.find_all, return all the odd numbers from the following array: [1,2,3,4,5,6,7,8]

Return all odd numbers from [1,2,3,4,5,6,7,8]



a.select { |num| num % 2 == 1 }


This returns all numbers that have a remainder of 1 when divided by 2, aka odd numbers.


OR


a.select { |num| num.odd? }

Which Enumerable method is the opposite of .select/.find_all? (Or rather, which Enumerable searches a collection and returns the elements for which the given block returns false?)

Answer: .reject


Using the .reject method, return arrays of only even and only odd numbers from the range (1...10).

To return the even numbers:


(1..10).reject {|num| num.odd?}


OR (1..10).reject {|num| num %2 == 1}



To return the odd numbers:


a.reject {|num| num.even?}


OR (1..10).reject {|num| num %2 == 0}

Using .select/.find_all, pull Rachel, Steve and Jorge from the following array based on the number of letters in their names:


staff = ["rachel", "steve", "jorge", "josh", "jeff"]



Then use .reject to end up with an array that contains just Josh and Jeff.

staff = ["rachel", "steve", "jorge", "josh", "jeff"]



staff.select {|name| name.length > 4}


=> ["rachel", "steve", "jorge"]



staff.reject {|name| name.length > 4}


=> ["josh", "jeff"]

What will be returned as a result of the following code?


batman = ["keaton", "kilmer", "clooney", "bale"]
batman.find { |name| name.length >= 6}

Answer: "keaton"


The .find method returns only the first element that is true.


Though three of the four most recent Batman actors have names with 6 or more letters, only Michael Keaton is returned since he is found first.



Note: .find is also known as .detect

When .find/.detect cannot locate any element that returns true, the ifnone method is called, resulting in nil. What do the following examples return?


Example 1


(1..10).detect { |i| i % 5 == 0 and i % 7 == 0 }


Example 2


(1..100).find { |i| i % 5 == 0 and i % 7 == 0 }

Example 1 answer: nil


Example 2 answer: 35



In example 1, there is no number between 1 and 10 that can be divided exactly by 5 and by 7, so ifnone then nil.



In example 2, 35 is the first number between 1 and 100 that can be divided exactly by 5 and 7.

The following Enumerable methods return _____ or _____.



.all?


.any?


.none?


.one?

Answer: true or false



.all? returns true if the block never returns false or nil.


.any? returns true if the block ever returns a value other than false or nil.


.none? returns true if the block never returns true for all elements.


.one? returns true if the block returns true exactly once.

True or false?



example 1: %w[man bear pig].all? { |word| word.length >= 3 }



example 2: %w[man bear pig].all? { |word| word.length >= 4 }



example 3: [nil, true, 16].all?

Because we are using the .all? method, which returns true if the block never returns false or nil:



example 1: true. All word lengths in the array are >=3/true.


example 2: false. Only one word length in the array is >= 4/true.


example 3: false. One of the elements is nil.




True or false?



example 1: %w[man bear pig].any? { |word| word.length >= 3 }



example 2: %w[man bear pig].any? { |word| word.length >= 4 }



example 3: [nil, true, 16].any?

Because we are using the .any? method, which returns true if the block ever returns a value other than false or nil, all of those examples return true, even example 3.

True or false?



example 1: %w[man bear pig].none? { |word| word.length >= 5 }


example 2: %w[man bear pig].none? { |word| word.length >= 4 }


example 3: [ ].none?


example 4: [nil].none?


example 5: [nil, false].none?

Because we are using the .none? method, which returns true if the block never returns true for all elements, only example 2 is false.

True or false?



example 1: %w[man bear pig].one? { |word| word.length == 4 }


example 2: %w[man bear pig].one? { |word| word.length > 4 }


example 3: %w[man bear pig].one? { |word| word.length < 4 }


example 4: [nil, true, 58].one?


example 5: [nil, true, false].one?

Because we are using the .one? method, which returns true if the block returns true only once:



example 1: true. Only one word length == 4.


example 2: false. No words are greater than 4 letters long.


example 3: false. More than one word is less than 4 letters long.


example 4: false. More than one element is true.


example 5: true. True is the only true element in the array.

Which Enumerable method would you use to quickly determine whether spinach is present within the following hash? What about broccoli?



veg = {"carrots"=>5, "turnip"=>1, "beet"=>2, "cucumber"=>4, "radish"=>1, "swiss chard"=>3, "green pepper"=>2, "red onion"=>4, "potato"=>5, "spinach"=>1, "eggplant"=>1, "arugula"=>2, "corn"=>3, "string bean"=>6, "kale"=>4, "yam"=>1, "pea"=>25, "jicama"=>1}

Answer: .include?



veg.include?("spinach") => true


veg.include?("broccoli") => false

The .zip method passes in elements from multiple arrays and puts them into subarrays based on index location. What is the result of the following code?


a = ["nutella", "potato", "spicy tuna"]


b = ["crepe", "samosa", "sushi"]



["france", "india", "japan"].zip(a, b)

Result: an array of delicious subarrays:


[["france", "nutella", "crepe"],
["india", "potato", "samosa"],
["japan", "spicy tuna", "sushi"]]



Before we zipped, the index locations of each array corresponded to a particular country/food. After .zip, the countries/foods are grouped into their own subarrays. Note how .zip ordered these elements. Play in pry.

.zip results depend on the length of the arrays involved.


a = ["nutella", "potato", "spicy tuna"]


b = ["crepe", "samosa", "sushi"]



What happens if you add a country?


["france", "india", "japan", "italy"].zip(a, b)

In the case of unequal content, things default to the length of the .zip array (or hash). If you add a country, a 4th subarray is created, but because there are no items in a or b that have index locations of 3, the empty spots in the subarray are filled in with nil:



["france", "india", "japan", "italy"].zip(a, b)


=> [["france", "nutella", "crepe"], ["india", "potato", "samosa"],
["japan", "spicy tuna", "sushi"], ["italy", nil, nil]]


.zip results depend on the length of the arrays involved, cont.



a = ["nutella", "potato", "spicy tuna"]


b = ["crepe", "samosa", "sushi"]



What happens if you zip in only two countries?


["france", "india"].zip(a, b)

In the case of unequal content, things default to the length of the .zip array (or hash). If you call zip on something with fewer elements than the other collections that you're working with, index locations that don't exist in the .zip array (or hash) will be ignored.



["france", "india"].zip(a, b)
=> [["france", "nutella", "crepe"], ["india", "potato", "samosa"]]

You can also use the .zip method to combine two arrays into a hash.


musicians => ["Jim", "Josie", "Leon", "Liz"]


instruments => ["vocals", "bass", "guitar", "drums"]


band = Hash[musicians.zip(instruments)]


=> {"Jim"=>"vocals", "Josie"=>"bass", "Leon"=>"guitar", "Liz"=>"drums"}


Now you try. Using .zip, combine the following arrays into a hash:


english = ["chicken", "water", "house"], spanish = ["pollo", "aqua", "casa"]

english = ["chicken", "water", "house"]


spanish = ["pollo", "aqua", "casa"]



Answer: Hash[english.zip(spanish)]



=> {"chicken"=>"pollo", "water"=>"aqua", "house"=>"casa"}

The .group_by method creates a new hash. What does the following code return?



birds = ["horned owl", "eagle", "hawk", "rook", "sparrow", "robin", "seagull", "hummingbird"]



b = birds.group_by { |letter| letter[0] }

b = birds.group_by { |letter| letter[0] }


=> {"h"=>["horned owl", "hawk", "hummingbird"],
"e"=>["eagle"],
"r"=>["rook", "robin"],
"s"=>["sparrow", "seagull"]}



You now have a new hash where the first letter of each bird name (the letter in index location zero) is the key and the birds are the values.

Using the .group_by method, create a new hash that organizes the big cats in the following array by the length of their names:



cats = ["tiger", "lion", "puma", "leopard", "jaguar", "cheetah", "bobcat"]

cats = ["tiger", "lion", "puma", "leopard", "jaguar", "cheetah", "bobcat"]



Answer: cats.group_by { |cat| cat.length}


=> {5=>["tiger"], 4=>["lion", "puma"], 7=>["leopard", "cheetah"], 6=>["jaguar", "bobcat"]}



Note that hashes aren't meant to be in a certain order. The relationship between keys and values is what is important in a hash.

The .max_by method returns the object that gives the maximum value from the given block. What does the following code return?



a = %w(taco quesadilla burrito)


a.max_by { |x| x.length }

Answer: "quesadilla"



You created a new array full of three delicious food items. You then called the .max_by method on the array and asked for the maximum item length, so quesadilla is the result.


The opposite of .max_by is, surprise, the .min_by method. Using the .min_by method and the array below, return the string "taco":



a = ["quesadilla", "taco", "burrito"]


a = ["quesadilla", "taco", "burrito"]



Answer: a.min_by { |x| x.length }


=> "taco"


The .count method does exactly that. What do the following code examples return?


a = [1, 2, 4, 2]



a.count


a.count(2)


a.count{ |x| x%2==0 }

a = [1, 2, 4, 2]



a.count => 4 There are 4 items in the array.


a.count(2) => 2 If an argument is given, the number of items that equal the argument counted. There are 2 items in the array that == 2.


a.count{ |x| x%2==0 } => 3 If a block is given, the number of elements that equal true are counted. In this case, 2 (twice) and 4 both have a zero remainder when divided by 2.