Arrays Flashcards
What does “each” method return on an array?
It always returns the original array. e.g. x = [1, 2, 3, 4, 5] x.each do |a| a + 1 end
=>[1, 2, 3, 4, 5]
What do “array.first” and “array.last” do? (+examples)
They return the first and the last element of the array.
e.g.
array = [1,2,3,4,5]
array.first
=>1
array.last
=>5
What are the two result
options after a method is evaluated?
It either returns new data or modifies the original data.
new data:(does not mutate the caller)
.sort (arranges numbers in the array in order)
modifies: (mutate the caller)
.pop (takes the last element of the array)
How do you add an argument to the beginning and take one away from the end of a(n) array/list?
a = [3,4,5,6]
a.unshift(10)
=> [10,3,4,5,6]
a.pop
=>[10,3,4,5]
How to add an item back to the array permanently?
a = [2,5,6]
a.push(3)
=>[2,5,6,3]
What is the alternative to the .pop method?
«
a = [2,3,4,6]
a «_space;6
=>[2,3,4]
What is the difference between .map and .collect methods and how do they work?
They are the same.
a = [1,2,3,4]
a.collect {|num| num*5}
=> [5,10,15,20]
a.map {|num| num*5}
=> [5,10,15,20]
What is the difference between the “delete” and “delete_at” methods?
Both can delete an element
from the array, the “delete_at” targets it by its index (array[2]) while the “delete” targets it by its value (array[“lemon”]).
Both mutate the caller.
How can you iterate through an array and delete the duplicated values?
With the .uniq method. e.g. array = [1,2,3,4,2,1,3,2,1] array.uniq => [1,2,3,4]
It doesn’t mutate the caller.
Write a method that iterates through an array and return those numbers that are less than 8!
array = [2,6,9,8,12,1,4,7,25]
array.select {|num| num < 8}
What is the alternative to the .pop method?
«
a = [2,3,4,6]
a «_space;6
=>[2,3,4]
What is the difference between .map and .collect methods and how do they work?
They are the same.
a = [1,2,3,4]
a.collect {|num| num*5}
=> [5,10,15,20]
a.map {|num| num*5}
=> [5,10,15,20]
What is the difference between the “delete” and “delete_at” methods?
Both can delete an element
from the array, the “delete_at” targets it by its index (array[2]) while the “delete” targets it by its value (array[“lemon”]).
Both mutate the caller.
How can you iterate through an array and delete the duplicated values?
With the .uniq method. e.g. array = [1,2,3,4,2,1,3,2,1] array.uniq => [1,2,3,4]
It doesn’t mutate the caller.
Write a method that iterates through an array and return those numbers that are less than 8!
array = [2,6,9,8,12,1,4,7,25]
array.select {|num| num < 8}
=> [2,6,1,4,7]