How can I check if all the numbers in this array are even numbers?
arr = [2, 4, 6, 8]
arr.all?(&:even?)
How can I check if the numbers in this array are NOT even numbers?
arr = [2, 4, 6, 8]
arr.none?(&:even?)
How can I check if any of the numbers in this array are odd numbers?
arr = [2, 4, 7, 8, 9]
arr.any?(&:odd?)
How can I check if just a single number in this array is an odd number?
arr = [2, 4, 7, 8]
arr.one?(&:odd?)
How can I split an array based on all the values that evaluate to true and all the values that evaluate to false?
Separate out the even vs. odd numbers
arr = [2, 4, 7, 8, 9]
arr. partition(&:even?)
output: [2,4,8] [7,9]
How can I check if the array does not contain any duplicate elements?
arr = [2, 4, 7, 8, 9, 7, 2]
arr.uniq.length == arr.length
Reducing the array to just the uniques and seeing if the length of the reduced array and original array are the same
How can I return a new array to just the even numbers?
arr = [2, 4, 7, 8, 9, 7, 2]
arr.select(&:even?)
or can be written
arr.select { |num| num.even? }
How can I merge two arrays together to have corresponding elements of the same indices together?
array_a = [ 4, 5, 6 ] array_b = [ 7, 8, 9 ]
array_a.zip(array_b)
output: [[4, 7], [5, 8], [6, 9]]
What happens when you merge two arrays together at corresponding indices but the two arrays have different lengths?
array_a = [ 4, 5, 6 ] array_b = [ 7 ] array_c = [ 1, 2]
Need to zip with the largest array first with the other smaller arrays listed as the parameters to make sure all values are captured. Any empty values will appear as “nil”
array_a = [ 4, 5, 6 ] array_b = [ 7 ] array_c = [ 1, 2]
array_a.zip(array_b, array_c)
output : [[4, 7, 1], [5, nil, 2], [6, nil, nil]]
Return a new array with the start number and length provided and multiply each number by 2
p test(2, 4)
def test(start, length)
arr = [start]
(0...length-1).map { |i| arr << arr[-1] * 2 }
arr
endoutput: [2, 4, 8, 16]
What type of enumerable allows you to iterate through an array and accrue information over the duration of the iteration?
What are the different ways this enumerable can be used?
What is it synonymous with?
.inject is interchangeable with .reduce
If you do not explicitly specify an initial value for memo, then the first element of collection is used as the initial value of memo.
Ways to use it:
array = [1, 5, “dog”, :yes, 6, 1000, “three-hundred”]
in this example, i’m using an empty array as my initial value and then shoveling into the array only the integers multiplied by 3
a = ["Sally", "Beatrice", "Bob", "Molly"] b = ["421-4921", "293-1839", "104-1273", "483-2894"]
output :
{“Sally”=>”421-4921”, “Beatrice”=>”293-1839”, “Bob”=>”104-1273”, “Molly”=>”483-2894”}
Iterate through this array and return a new array with the element and their corresponding indices in individual sub-arrays
arr = [2, 4, 7, 8, 9, 7, 2]
def test(arr)
result = []
arr.each_with_index { |e, i| result << [e,i] }
result
endoutput: [[2, 0], [4, 1], [7, 2], [8, 3], [9, 4], [7, 5], [2, 6]]
Write a method combinations that takes in an array of unique elements, the method should return a 2D array representing all possible combinations of 2 elements of the array.
arr = ([“a”, “b”, “c”])
To create a 2D array from a single array requires iterating through the same array twice and to find unique combinations with no duplicates, need to make sure the index of the inner array is greater than the indices in outer array
def test(arr)
pairs = []
arr.each_with_index do |ele_1, idx_1|
arr.each_with_index do |ele_2, idx_2|
pairs «_space;[ele_1, ele_2] if idx_2 > idx_1
end
end
pairs
end
What is a symbol?
Symbols are designated by “ : “ and cannot be immutable,. and will have the same object ID throughout the code. While it cannot be reassigned, the characteristics of the symbol can be changed.
str = "hello" sym = :hello
str[0] = "x" sym[0] = "x"
p str # => “xello”
p sym # => :hello
Symbols can also be used as hash keys { :name = “Ann” }
hash[:name]
What is a splat? What are the 3 ways of using it?
arr_1 = [“a”, “b”]
arr_2 = [“d”, “e”]
arr_3 = [ *arr_1, “c”, *arr_2 ]
p arr_3 # => [“a”, “b”, “c”, “d”, “e”]
old_hash = { a: 1, b: 2 }
new_hash = { **old_hash, c: 3 }
p new_hash # => {:a=>1, :b=>2, :c=>3}
What are the two ways to create a GLOBAL scope that can accessed outside of a method?
2. Using CAPITAL letters to create a “Constant” variable. a Constant variable like a symbol cannot be reassigned.
What is lexical scope?
Lexical scope describes how a variable name evaluates in nested code. All methods have local scopes.
What is an algorithm?
Sequence of actions to complete a task - sorting algorithms
How do you implement a bubble sort algorithm?
arr = [2, 9, 4, 5, 6, 1]
def bubble_sort(arr)
sorted = true
while sorted
sorted = false
(0...arr.length-1).each do |i|
if arr[i] > arr[i+1]
arr[i], arr[i+1] = arr[i+1], arr[i]
sorted = true
end
end
end
arr
endoutput: [1, 2, 4, 5, 6, 9]
What is one way to handle a native exception like ZeroDivisionError?
Ways to raise an error
“Begin…rescue” (Under “begin” you insert the code that would occur when it can be successfully run. Under “rescue” you put the desired output for when there’s an error”
begin
puts "dividing 10 by #{num}"
ans = 10 / num
puts "the answer is #{ans}"
rescue
puts "There was an error with that division."
endWrite a method, my_rotate!(array, amt), that accepts an array and a number as args.
The method should mutate the array by rotating the elements ‘amt’ number of times.
When given a positive ‘amt’, a single rotation will rotate left, causing the first element to move to the last index
When given a negative ‘amt’, a single rotation will rotate right, causing the last element to move to the first index
The method should return the given array. Do not use the built-in Array#rotate
def my_rotate!(array, amt)
if amt > 0
amt.times {
first = array.shift
array.push(first) }
elsif amt < 0
amt.abs.times {
last = array.pop
array.unshift(last) }
end
array
endarray_1 = [“a”, “b”, “c”, “d”]
result_1 = my_rotate!(array_1, 2)
p result_1 # => [“c”, “d”, “a”, “b”]
array_2 = [“NOMAD”, “SOHO”, “TRIBECA”]
result_2 = my_rotate!(array_2, 1)
p result_2 # => [“SOHO”, “TRIBECA”, “NOMAD”]
array_3 = [“a”, “b”, “c”, “d”]
result_3 = my_rotate!(array_3, -3)
p result_3 # => [“b”, “c”, “d”, “a”]
Write a method that return true or false if an array is sorted or not.
def is_sorted(arr)
(0...arr.length-1).each do |i|
if arr[i] > arr[i+1]
return false
end
end
return true
end
p is_sorted([1, 4, 10, 13, 15]) # => true p is_sorted([1, 4, 10, 10, 13, 15]) # => true p is_sorted([1, 2, 5, 3, 4 ]) # => false
How do you implement a bubble sort alogrithm with the below array?
arr = [2, 9, 4, 5, 6, 1]
def bubble_sort(arr)
Write a method, compress_str(str), that accepts a string as an arg. The method should return a new str where streaks of consecutive characters are compressed. For example “aaabbc” is compressed to “3a2bc”.
def compress_str(str)
compressed = ""
i = 0
while i < str.length
char = str[i]
count = 0
while char == str[i]
count += 1
i += 1
end
count == 1 ? (compressed += char) : (compressed += count.to_s + char)
end
compressed
end
p compress_str("aaabbc") # => "3a2bc"
p compress_str("xxyyyyzz") # => "2x4y2z"
p compress_str("qqqqq") # => "5q"
p compress_str("mississippi") # => "mi2si2si2pi"